Does acccessing nested FK relation's field value downgrade performance?

Viewed 32

I have various models which are interconnected through Foreign key relations, does doing this make any performance downside. I want to know how does django perform this internally.

PriceSheet.objects.select_related('query').filter(
    id=pricesheet_id
).values(
    'query__campaign_name', 'query_id', 'query__campaign_status',
    'query__lead_id', 'query__lead__legal_name', 'query__lead__brand_name' # nested
    'query__lead__working_capital', 'query__lead__payment_terms'
)  # 7
1 Answers

You can inspect the query by printing:

print(queryset.query)

In that case Django will print the query that it will make. In this case, the query will look like:

SELECT query.campaign_name, price_sheet.id, query.campaign_status,
       query.lead_id, lead.legal_name, lead.brand_name,
       lead.working_capital, lead.payment_terms
FROM price_sheet
LEFT OUTER JOIN query ON query.id = price_sheet.query_id
LEFT OUTER JOIN lead ON lead.id = query.lead_id
WHERE price_sheet.id = pricesheet_id

Django will thus make JOINs on the models referenced by the query and by the lead of the query. Using .select_related(…) [Django-doc] to force a JOIN is not necessary in this case.

Usually it is better not to work with .values(…) [Django-doc] when you want to convert data to a JSON blob, since it erodes the logical layer that the model(s) provide. For a field with choices for example, you can no longer (easily) access the display name, etc.

Related