3

I have models like this

Model Trip:
  hotel: m2m_field to Hotel
  flight: m2m_field to Flight
Model Hotel:
  city: foreignkey to City
Model Flight:
  city: foreignkey to City

The problem is when I do

Trip.objects.prefetch_related('hotel__city', 'flight__city')

It generates 5 sql queries: 1 on Trip, 1 on Hotel, 1 on Flight, 1 on City from Hotel result, and 1 on City from Flight result. Can I reduce the last two queries on City table into 1? I think I may be asking too much from ORM, but just want to know whether it's possible either in ORM or raw-query.

1 Answer 1

1

prefetch_related will always perform separate queries - from the docs:

prefetch_related(**lookups) - Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.

If you're looking to combine queries, you should be using select_related, which in this instance will perform a single query with four joins to the hotel, flight & city(x2) tables.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.