Search code examples
djangodjango-modelsdjango-viewsdjango-select-related

Django Select Related


i want to filter the database like this .

qs = profile.objects.filter().select_related('profile_detail').select_related('location')

But here location is a foreignkey in profile_detail model. So how can i do that query

class Location(models.Model):
      place = models.CharField(max_length=128)

 class ProfileDetail(models.Model):
     location = models.ForiegnKey(Location)

  class Profile(models.Model):
      detail = models.ForeignKey(ProfileDetail)

Solution

  • You can use related lookup query syntax __

    https://docs.djangoproject.com/en/1.10/topics/db/queries/#lookups-that-span-relationships

    qs = profile.objects.filter().select_related('detail__location')
    

    And it should detail not profile_detail. Just as your field in Profile called