Django select_related () for multiple connection query using models and filters

I have two models: Job and Location:

class Job(models.Model):
   title = models.CharField(max_length=20)
   company = models.CharField(max_length=20)
   location = ForeignKey('Location')

class Location(models.Model):
   country = models.CharField(max_length=20)
   state = models.CharField(max_length=20)
   city = models.CharField(max_length=20)
   latitude = models.FloatField(blank=True, default=0.0)
   longitude = models.FloatField(blank=True, default=0.0)
   big-city = ForeignKey('Location')

      

Let's say: My database has USA / California / San France, USA / California / San_Jose, USA / California / Alameda, and USA / California / Oakland. I also have a manager / Ebay / San-Fran, an accountant / Amazon / San-Jose, Coop / IBM / Oakland, and a director / Dell / Alameda.

Also: San Fran is like a big_city in its own right, while San Jose, Alameda and Oakland have San Fran in their big city.

Now I make a request like this when someone searches all jobs in San-Fran.

Job.objects.filter(
location__country='US', 
location__state='Calif', 
location__city='San-Fran').selected_related('Location')

      

However, I would like to allow search by regions where the user can search for all jobs in the San France region. Will it be all works in San France, Oakland, Alameda and San Jose?

Like "Show me all assignments where their location references other locations."

Will this be called a double join?

Ideally, I would use lat-lon-radius (later exercise), but for now I want to know how to do it with a double join.

thanks.

Vn44ca

+1


a source to share


1 answer


Here's a query that should do what you want:

Job.objects.filter(location__big_city__city='San-Fran', location__big_city__state='Calif', location__big_city__country='USA')

      



Indeed, Django uses the Location table join twice when doing this query:

SELECT "example_job"."id", "example_job"."title", "example_job"."company", "example_job"."location_id" FROM "example_job" INNER JOIN "example_location" ON ("example_job"."location_id" = "example_location"."id") INNER JOIN "example_location" T3 ON ("example_location"."big_city_id" = T3."id") WHERE (T3."country" = USA  AND T3."city" = San-Fran  AND T3."state" = Calif

      

+1


a source







All Articles