Skip to content
Advertisement

Django get data from related model which has the FK

how can i make this queryset:

SELECT 
  p.*,
  o.name,
  o.link
FROM property p
INNER JOIN listing l on l.property_id = p.id
INNER JOIN ota o on o.id = l.ota_id

models

class Property(Model):
   code = CharField()
   ...

class Listing(Model):
   ota = ForeignKey(Ota)
   property = ForeignKey(Property)

class Ota(Model):
   name = Charfield()
   link = Charfield()

with Property.objects.all() I can see in the returned object that there is a listing_set

let say:

queryset = Property.objects.all()
queryset[0].listing_set.all()

but it brings the entire model, and not the related to property_id;

also tried to get Ota data in serializer with SerializerMethodField and perform a new query to get this info, but decrease performance significantly.

Advertisement

Answer

I think you should use related_name

related_name

class Property(Model):
   code = CharField()
   ...

class Listing(Model):
   ota = ForeignKey(Ota)
   property = ForeignKey(Property,related_name='listinings')

class Ota(Model):
   name = Charfield()
   link = Charfield()

and

pp=Property.objects.first()
pp.listinings.all()
Advertisement