0

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)
Thameem
  • 3,426
  • 4
  • 26
  • 32

1 Answers1

2

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

Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
  • can we use related name instead of field name here . detail = models.ForeignKey(ProfileDetail, related_name="pdetail") qs = profile.objects.filter().select_related('pdetail__location') – Thameem Oct 20 '16 at 11:02
  • 1
    @Thameem No. related name is used in reverse lookups. For example if you have `profie_detail` object. Then you can do this `profile_detail.pdetail.all()` to get all profiles with this `profile_detail` – Sardorbek Imomaliev Oct 20 '16 at 11:05