Automatic prefetching in querysets

2,049 views
Skip to first unread message

Gordon Wrigley

unread,
Aug 15, 2017, 5:44:19 AM8/15/17
to Django developers (Contributions to Django itself)
I'd like to discuss automatic prefetching in querysets. Specifically automatically doing prefetch_related where needed without the user having to request it.

For context consider these three snippets using the Question & Choice models from the tutorial when there are 100 questions each with 5 choices for a total of 500 choices.

Default
for choice in Choice.objects.all():
   
print(choice.question.question_text, ':', choice.choice_text)
501 db queries, fetches 500 choice rows and 500 question rows from the DB

Prefetch_related
for choice in Choice.objects.prefetch_related('question'):
   
print(choice.question.question_text, ':', choice.choice_text)
2 db queries, fetches 500 choice rows and 100 question rows from the DB

Select_related
for choice in Choice.objects.select_related('question'):
   
print(choice.question.question_text, ':', choice.choice_text)
1 db query, fetches 500 choice rows and 500 question rows from the DB

I've included select_related for completeness, I'm not going to propose changing anything about it's use. There are places where it is the best choice and in those places it will still be up to the user to request it. I will note that anywhere select_related is optimal prefetch_related is still better than the default and leave it at that.

The 'Default' example above is a classic example of the N+1 query problem, a problem that is widespread in Django apps.
This pattern of queries is what new users produce because they don't know enough about the database and / or ORM to do otherwise.
Experieced users will also often produce this because it's not always obvious what fields will and won't be used and subsequently what should be prefetched.
Additionally that list will change over time. A small change to a template to display an extra field can result in a denial of service on your DB due to a missing prefetch.
Identifying missing prefetches is fiddly, time consuming and error prone. Tools like django-perf-rec (which I was involved in creating) and nplusone exist in part to flag missing prefetches introduced by changed code.
Finally libraries like Django Rest Framework and the Admin will also produce queries like this because it's very difficult for them to know what needs prefetching without being explicitly told by an experienced user.

As hinted at the top I'd like to propose changing Django so the default code behaves like the prefetch_related code.
Longer term I think this should be the default behaviour but obviously it needs to be proved first so for now I'd suggest a new queryset function that enables this behaviour.

I have a proof of concept of this mechanism that I've used successfully in production. I'm not posting it yet because I'd like to focus on desired behavior rather than implementation details. But in summary, what it does is when accessing a missing field on a model, rather than fetching it just for that instance, it runs a prefetch_related query to fetch it for all peer instances that were fetched in the same queryset. So in the example above it prefetches all Questions in one query.

This might seem like a risky thing to do but I'd argue that it really isn't.
The only time this isn't superior to the default case is when you are post filtering the queryset results in Python.
Even in that case it's only inferior if you started with a large number of results, filtered basically all of them and the code is structured so that the filtered ones aren't garbage collected.
To cover this rare case the automatic prefetching can easily be disabled on a per queryset or per object basis. Leaving us with a rare downside that can easily be manually resolved in exchange for a significant general improvement.

In practice this thing is almost magical to work with. Unless you already have extensive and tightly maintained prefetches everywhere you get an immediate boost to virtually everything that touches the database, often knocking orders of magnitude off page load times.

If an agreement can be reached on pursuing this then I'm happy to put in the work to productize the proof of concept.

Marc Tamlyn

unread,
Aug 15, 2017, 2:03:07 PM8/15/17
to django-d...@googlegroups.com
Hi Gordon,

Thanks for the suggestion.

I'm not a fan of adding a layer that tries to be this clever. How would possible prefetches be identified? What happens when an initial loop in a view requires one prefetch, but a subsequent loop in a template requires some other prefetch? What about nested loops resulting in nested prefetches? Code like this is almost guaranteed to break unexpectedly in multiple ways. Personally, I would argue that correctly setting up and maintaining appropriate prefetches and selects is a necessary part of working with an ORM.

Do you know of any other ORMs which attempt similar magical optimisations? How do they go about identifying the cases where it is necessary?

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-developers+unsubscribe@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/d402bf30-a5af-4072-8b50-85e921f7f9af%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Gordon Wrigley

unread,
Aug 15, 2017, 2:44:46 PM8/15/17
to django-d...@googlegroups.com
Sorry maybe I wasn't clear enough about the proposed mechanism.

Currently when you dereference a foreign key field on an object (so 'choice.question' in the examples above) if it doesn't have the value cached from an earlier access, prefetch_related or select_related then Django will automatically perform a db query to fetch it. After that the value will then be cached on the object for any future dereferences.

This automatic fetching is the source the N+1 query problems and in my experience most gross performance problems in Django apps.

The proposal essentially is to add a new queryset function that says for the group of objects fetched by this queryset, whenever one of these automatic foreign key queries happens on one of them instead of fetching the foreign key for just that one use the prefetch mechanism to fetch it for all of them.
The presumption being that the vast majority of the time when you access a field on one object from a queryset result, probably you are going to access the same field on many of the others as well.

The implementation I've used in production does nest across foreign keys so something (admittedly contrived) like:
for choice in Choice.objects.all():
    
print(choice.question.author)
Will produce 3 queries, one for all choices, one for the questions of those choices and one for the authors of those questions.

It's worth noting that because these are foreign keys in their "to one" direction each of those queryset results will be at most the same size (in rows) as the proceeding one and often (due to nulls and duplicates) smaller.

I do not propose touching reverse foreign key or many2many fields as the generated queries could request substantially more rows from the DB than the original query and it's not at all clear how this mechanism would sanely interact with filtering etc. So this is purely about the forward direction of foreign keys.

I hope that clarifies my thinking some.

Regards
G

--
You received this message because you are subscribed to a topic in the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-developers/EplZGj-ejvg/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-developers+unsubscribe@googlegroups.com.

To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.

Collin Anderson

unread,
Aug 15, 2017, 3:04:19 PM8/15/17
to django-d...@googlegroups.com
Hi Gordon,

How is it implemented? Does each object keep a reference to the queryset it came from?

Collin

Gordon Wrigley

unread,
Aug 15, 2017, 3:10:27 PM8/15/17
to django-d...@googlegroups.com
In my current version each object keeps a reference to a WeakSet of the results of the queryset it came from.
This is populated in _fetch_all and if it is populated then ForwardManyToOneDescriptor does a prefetch across all the objects in the WeakSet instead of it's regular fetching.

Tom Forbes

unread,
Aug 15, 2017, 3:18:05 PM8/15/17
to django-d...@googlegroups.com
Exploding query counts are definitely a pain point in Django, anything to improve that is definitely worth considering. They have been a problem in all Django projects I have seen.

However I think the correct solution is for developers to correctly add select/prefetch calls. There is no general solution for automatically applying them that works for enough cases, and i think adding such a method to querysets would be used incorrectly and too often. 

Perhaps a better solution would be for Django to detect these O(n) query cases and display intelligent warnings, with suggestions as to the correct select/prefetch calls to add. When debug mode is enabled we could detect repeated foreign key referencing from the same source.

Gordon Wrigley

unread,
Aug 15, 2017, 3:20:50 PM8/15/17
to django-d...@googlegroups.com
I didn't answer your questions directly. Sorry for the quoting but it's the easiest way to deal with a half dozen questions.

How would possible prefetches be identified?

Wherever we currently automatically fetch a foreign key value.

What happens when an initial loop in a view requires one prefetch, but a subsequent loop in a template requires some other prefetch?

They each do whatever prefetch they need, just as a human optimizing this would add two prefetch clauses.

What about nested loops resulting in nested prefetches?

Nested loops only really come up when you are dealing with RelatedManagers which are outside the scope of this. Or did you have some other nested loop case in mind?

 I would argue that correctly setting up and maintaining appropriate prefetches and selects is a necessary part of working with an ORM.

Having been lead engineer on a code base of ~100,000 lines with over 100 calls to prefetch_related and a lot of tests specifically for finding missing ones I'd argue it's one of the worst aspects of working with Djangos ORM at non trivial scale.

Do you know of any other ORMs which attempt similar magical optimisations? 

I don't, but unlike Django where I have years of experience I have next to no experience with other ORM's.

Regards G

Gordon Wrigley

unread,
Aug 15, 2017, 3:35:36 PM8/15/17
to django-d...@googlegroups.com
The warnings you propose would certainly be an improvement on the status quo.
However for that to be a complete solution Django would also need to detect places where there are redundant prefetch_relateds.

Additionally tools like the Admin and DRF would need to provide adequate hooks for inserting these calls.
For example ModelAdmin.get_queryset is not really granular enough as it's used by both the list and detail views which might touch quite different sets of fields. (Although in practice what you generally do is optimize the list view as that's the one that tends to explode)

That aside I sincerely believe that the proposed approach is superior to the current default behavior in the majority of cases and further more doesn't fail as badly as the current behavior when it's not appropriate. I expect that if implemented as an option then in time that belief would prove itself.

Adam Johnson

unread,
Aug 15, 2017, 5:30:10 PM8/15/17
to django-d...@googlegroups.com
I'm biased here, Gordon was my boss for nearly three years, 2014-2016.

I'm in favour of adding the auto-prefetching, I've seen it work. It was created around midway through last year and applied to our application's Admin interface, which was covered in tests with django-perf-rec. After adding the automatic prefetch, we not only identified some existing N+1 query problems that hadn't been picked up (they were there in the performance record files, just there were so many queries humans had missed reading some), we also found a number of stale prefetch queries that could be removed because the data they fetched wasn't being used. Additionally not all of the admin interface was perf-rec-tested/optimized so some pages were "just faster" with no extra effort.

I think there's a case for adding it to core - releasing as a third party package would make it difficult to use since it requires changes - mostly small - to QuerySet, ForeignKey, and the descriptor for ForeignKey. Users of such a package would have to use subclasses of all of these, the trickiest being ForeignKey since it triggers migrations... We had the luxury in our codebase of already having these subclasses for other customizations, so it was easier to roll out.


For more options, visit https://groups.google.com/d/optout.



--
Adam

Josh Smeaton

unread,
Aug 15, 2017, 6:05:08 PM8/15/17
to Django developers (Contributions to Django itself)
I'm in favour of *some* automated way of handling these prefetches, whether it's opt-in or opt-out there should be some mechanism for protection. Preferably with loud logging that directs users to the source of the automated hand-holding so they have an opportunity to disable or fine tune the queries. Not all Django devs are ORM/Database/Python experts - some are frontend devs just trying to get by. I know that this kind of proposed behaviour would have both saved our site from massive performance issues, but also likely guided these same devs to the source of potential issues.

Agreed that prefetch_related is strictly better than not, and is acceptable in the absence of select_related.

I think keeping the code back and focussing on the idea first is a good one. I think I'd like to know whether people thought that opt-in or opt-out behaviour would be best?

For me - there are a few cases where automatically prefetching would *maybe* be the wrong thing to do. In the vast majority of cases it'd be better than the default of having nothing.

A few concerns:

- Be careful of `.iterator()` queries (that can't use prefetch)
- Could we warn of reverse M2M/ForeignKey at least?

Adam/Gordon, I'm interested in hearing how these changes led you to discovering stale prefetches?
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To post to this group, send email to django-d...@googlegroups.com.

--
You received this message because you are subscribed to a topic in the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-developers/EplZGj-ejvg/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-develop...@googlegroups.com.

To post to this group, send email to django-d...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To post to this group, send email to django-d...@googlegroups.com.

--
You received this message because you are subscribed to a topic in the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-developers/EplZGj-ejvg/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-develop...@googlegroups.com.
To post to this group, send email to django-d...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To post to this group, send email to django-d...@googlegroups.com.



--
Adam

Luke Plant

unread,
Aug 15, 2017, 6:15:11 PM8/15/17
to django-d...@googlegroups.com

I agree with Marc here that the proposed optimizations are 'magical'. I think when it comes to optimizations like these you simply cannot know in advance whether doing extra queries is going to a be an optimization or a pessimization. If I can come up with a single example where it would significantly decrease performance (either memory usage or speed) compared to the default (and I'm sure I can), then I would be strongly opposed to it ever being default behaviour.

Concerning implementing it as an additional  QuerySet method like `auto_prefetch()` - I'm not sure what I think, I feel like it could get icky (i.e. increase our technical debt), due to the way it couples things together. I can't imagine ever wanting to use it, though, I would always prefer the manual option.

Luke

To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To post to this group, send email to django-d...@googlegroups.com.

Sean Brant

unread,
Aug 15, 2017, 6:20:43 PM8/15/17
to django-d...@googlegroups.com
I wonder if a solution similar to [1] from the rails world would satisfy this request. Rather then doing anything 'magical' we instead log when we detect things like accessing a related model that has not been pre-fetched.


--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-developers+unsubscribe@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.

Adam Johnson

unread,
Aug 15, 2017, 6:25:35 PM8/15/17
to django-d...@googlegroups.com
Adam/Gordon, I'm interested in hearing how these changes led you to discovering stale prefetches?

We removed all the manual prefetches in admin get_queryset() methods, added the auto_prefetch_related call, and regenerated the performance records from django-perf-rec tests that hit the admin classes on the list view, detail view, etc. Some queries disappeared and on inspection it was obvious they were for features since removed e.g. a related field no longer shown on the list view.

To unsubscribe from this group and stop receiving emails from it, send an email to django-developers+unsubscribe@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.



--
Adam

Adam Johnson

unread,
Aug 15, 2017, 6:32:36 PM8/15/17
to django-d...@googlegroups.com
I agree with Marc here that the proposed optimizations are 'magical'. I think when it comes to optimizations like these you simply cannot know in advance whether doing extra queries is going to a be an optimization or a pessimization.

I think Django automatically fetching data from the database on access is already magical, it certainly surprises new users (in good and bad ways) when they first come across it, especially if they've only worked with SQL before and not any other ORM's.

This is not doing "extra" queries, just fetching a bit more data. In the most likely case, there are far fewer queries - N+1 will instead become 2. I think it's a reasonable assumption that if choices_queryset[0].question is accessed, choices_queryset[1].question up to choices_queryset[n].question will be accessed too. The current behaviour is effectively assuming that it's completely unlikely.
--
Adam

Anthony King

unread,
Aug 15, 2017, 6:41:31 PM8/15/17
to django-d...@googlegroups.com
Automatically prefetching is something I feel should be avoided. 

A common gripe I have with ORMs is they hide what's actually happening with the database, resulting in beginners-going-on-intermediates building libraries/systems that don't scale well. 

We have several views in a dashboard, where a relation may be accessed once or twice while iterating over a large python filtered queryset. 
Prefetching this relation based on the original queryset has the potential to add around 5 seconds to the response time (probably more, that table has doubled in size since I last measured it). 

I feel it would be better to optimise for your usecase, as apposed to try to prevent uncalled-for behaviour. 



--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-developers+unsubscribe@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.

Josh Smeaton

unread,
Aug 15, 2017, 7:26:43 PM8/15/17
to Django developers (Contributions to Django itself)
I believe we should be optimising for the **common** use case, not expecting everyone to be experts with the ORM.


> If I can come up with a single example where it would significantly decrease performance (either memory usage or speed) compared to the default (and I'm sure I can), then I would be strongly opposed to it ever being default behaviour. 

The status quo is already one where thousands of users and sites are doing the non-optimal thing because we're choosing to be conservative and have users opt-in to the optimal behaviour. A massive complaint against Django is how easy it is for users to build in 1+N behaviour. Django is supposed to abstract the database away (so much so that we avoid SQL related terms in our queryset methods), yet one of the more fundamental concepts such as joins we expect users to know about and optimise for.

I'd be more in favour of throwing an error on non-select-related-foreign-key-access than what we're currently doing which is a query for each access.

The only options users currently have of monitoring poor behaviour is:

1. Add logging to django.db.models
2. Add django-debug-toolbar
3. Investigate page slow downs

Here's a bunch of ways that previously tuned queries can "go bad":

1. A models `__str__` method is updated to include a related field
2. A template uses a previously unused related field
3. A report uses a previously unused related field
4. A ModelAdmin adds a previously unused related field

I think a better question to ask is:

- How many people have had their day/site ruined because we think auto-prefetching is too magical?
- How many people would have their day/site ruined because we think auto-prefetching is the better default?

If we were introducing a new ORM, I think the above answer would be obvious given what we know of Django use today.

What I'd propose:

1. (optional) A global setting to disable autoprefetching
2. An opt out per queryset
3. (optional) An opt out per Meta?
4. Logging any autoprefetches - perhaps as a warning?

More experienced Django users that do not want this behaviour are going to know about a global setting and can opt in to the old behaviour rather easily. Newer users that do not know about select/prefetch_related or these settings will fall into the new behaviour by default.

It's unreasonable to expect every user of django learn the ins and outs of all queryset methods. I'm probably considered a django orm expert, and I still sometimes write queries that are non-optimal or *become* non-optimal after changes in unrelated areas. At an absolute minimum we should be screaming and shouting when this happens. But we can also fix the issue while complaining, and help guide users into correct behaviour.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To post to this group, send email to django-d...@googlegroups.com.
--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To post to this group, send email to django-d...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To post to this group, send email to django-d...@googlegroups.com.

Curtis Maloney

unread,
Aug 15, 2017, 7:34:50 PM8/15/17
to django-d...@googlegroups.com
The 2 goals of a famework:
- protect you from the tedious things
- protect you from the dangerous things

N+1 queries would be in the 'dangerous' category, IMHO, and 'detecting
causes of N+1 queries' is in the 'tedious'.

If we can at least add some DEBUG flagged machinery to detect and warn
of potential prefetch/select candidates, it would be a big win.

--
C
>> <gordon....@gmail.com <javascript:>> wrote:
>>
>> I'd like to discuss automatic prefetching in querysets.
>> Specifically automatically doing prefetch_related where
>> needed without the user having to request it.
>>
>> For context consider these three snippets using the
>> Question & Choice models from the tutorial
>> <https://docs.djangoproject.com/en/1.11/intro/tutorial02/#creating-models> when
>> <https://github.com/YPlan/django-perf-rec> (which I was
>> involved in creating) and nplusone
>> <https://github.com/jmcarp/nplusone> exist in part to flag
>> django-develop...@googlegroups.com <javascript:>.
>> To post to this group, send email to
>> django-d...@googlegroups.com <javascript:>.
>> <https://groups.google.com/group/django-developers>.
>> <https://groups.google.com/d/msgid/django-developers/d402bf30-a5af-4072-8b50-85e921f7f9af%40googlegroups.com?utm_medium=email&utm_source=footer>.
>> For more options, visit https://groups.google.com/d/optout
>> <https://groups.google.com/d/optout>.
>>
>>
>> --
>> You received this message because you are subscribed to the
>> Google Groups "Django developers (Contributions to Django
>> itself)" group.
>> To unsubscribe from this group and stop receiving emails from
>> it, send an email to django-develop...@googlegroups.com
>> <javascript:>.
>> To post to this group, send email to
>> django-d...@googlegroups.com <javascript:>.
>> <https://groups.google.com/group/django-developers>.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-developers/CAMwjO1Gaha-K7KkefJkiS3LRdXvaPPwBeuKmhQv6bJFx3dty3w%40mail.gmail.com
>> <https://groups.google.com/d/msgid/django-developers/CAMwjO1Gaha-K7KkefJkiS3LRdXvaPPwBeuKmhQv6bJFx3dty3w%40mail.gmail.com?utm_medium=email&utm_source=footer>.
>> For more options, visit https://groups.google.com/d/optout
>> <https://groups.google.com/d/optout>.
>
> --
> You received this message because you are subscribed to the
> Google Groups "Django developers (Contributions to Django
> itself)" group.
> To unsubscribe from this group and stop receiving emails from
> it, send an email to django-develop...@googlegroups.com
> <javascript:>.
> To post to this group, send email to
> django-d...@googlegroups.com <javascript:>.
> <https://groups.google.com/group/django-developers>.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-developers/a5780df6-ce60-05ae-88e3-997e6bc88f5c%40cantab.net
> <https://groups.google.com/d/msgid/django-developers/a5780df6-ce60-05ae-88e3-997e6bc88f5c%40cantab.net?utm_medium=email&utm_source=footer>.
> For more options, visit https://groups.google.com/d/optout
> <https://groups.google.com/d/optout>.
>
> --
> You received this message because you are subscribed to the Google
> Groups "Django developers (Contributions to Django itself)" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to django-develop...@googlegroups.com
> <mailto:django-develop...@googlegroups.com>.
> To post to this group, send email to django-d...@googlegroups.com
> <mailto:django-d...@googlegroups.com>.
> Visit this group at https://groups.google.com/group/django-developers.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-developers/2f0b5932-1a38-4eaf-84aa-13960a303141%40googlegroups.com
> <https://groups.google.com/d/msgid/django-developers/2f0b5932-1a38-4eaf-84aa-13960a303141%40googlegroups.com?utm_medium=email&utm_source=footer>.

Cristiano Coelho

unread,
Aug 16, 2017, 12:11:52 AM8/16/17
to Django developers (Contributions to Django itself)
I would rather have warnings as well, adding more magical behavior is bad and might even degrade performance on some cases, automatically selecting a bunch of data that "might" be used is bad, and specially considering how slow python is, accidentally loading/building 1k+ objects when maybe only one of them is used would be as bad as doing 1k+ queries.

If the systems you are building are that large and complicated you can't have people with 0 SQL knowledge doing stuff neither! So many things to tweak, indexes, data denormalization, proper joins here and there, unique constraints, locks and race conditions, someone attempting to code something that's not a blog or hello world really needs to know a bit about all of that.

Alexander Hill

unread,
Aug 16, 2017, 1:15:33 AM8/16/17
to Django developers (Contributions to Django itself)
I think this is an excellent suggestion.

It seems generally accepted in this thread that although there are cases where this would hurt performance, it would on average solve more problems than it creates. The debate seems to be more whether or not it's "right" for the ORM to behave in this magical way. With that in mind...

It won't affect experienced users. They'll read the release notes, see that this change has been implemented, and either go and delete a bunch of prefetch_related() calls, grumble a bit and turn auto-prefetch off globally or just file it away as another fact they know about the Django ORM.

For beginners, this can defer the pain of learning about N+1 problems, potentially forever depending on the scale of the project. Ultimately Django's job isn't to teach hard lessons about SQL gotchas, it's to make it easy to make a nice website. This proposal would reduce both average load time of Django pages and debugging time, at the cost of the average Django developer being a little more ignorant about what queries the ORM generates. I think that's a good trade and in line with the goals of the project.

Django's ORM isn't SQLAlchemy - it's built on high-level concepts, designed to be relatively beginner-friendly, and already pretty magical. select_related() and prefetch_related() are somewhat awkward plugs for a leaky abstraction, and IMO this is just a better plug.

Alex


--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To post to this group, send email to django-d...@googlegroups.com.

Brice Parent

unread,
Aug 16, 2017, 6:53:15 AM8/16/17
to django-d...@googlegroups.com

I almost agree with you... But I would make the behaviour an opt-in instead of an opt-out. I wouldn't like such a behaviour to be inserted with a simple version update.

What I wouldn't want is to give free optimisations to non-ORM pros at the cost of creating major unexpected or unneeded loads to already well optimized code bases (for which there would be close to no gain as the prefetch already exist where needed, and the only prefetch that would be added would be unnecessary).

Making it opt-in allows:

- for power ORM users not to use it at all without doing anything. We have to keep in mind that hose SQL experts may not be the ones that do the upgrades, so lead to unexpected efficiency loss without anyone to know where it comes from. As this functionality doesn't exist yet, probably no one has ever written any unit tests to guarantee that there is no unnecessary prefetch, which is the only way a non-expert would notice the upgrade is inserting a problem.

- for developers looking for better performances to set it on, but only in debug mode and local development to understand where they need to prefetch related fields. And when their code base is optimal, unset this option and remove the magic and any unwanted side effect. This would of course need to be documented in the pages about how to optimize and get better performances with Django.

- for new users or when creating applications mockups and proofs of concepts, they could set it on (the tutorial would talk a bit about it) and just use it, allowing them not to care about those optimizations that they don't need yet to take care of.

- Brice



Le 16/08/17 à 01:26, Josh Smeaton a écrit :

Josh Smeaton

unread,
Aug 16, 2017, 7:27:11 AM8/16/17
to Django developers (Contributions to Django itself)
It won't affect experienced users. They'll read the release notes, see that this change has been implemented, and either go and delete a bunch of prefetch_related() calls, grumble a bit and turn auto-prefetch off globally or just file it away as another fact they know about the Django ORM.

This is, for me, the biggest point in favour of having it opt out. It'll barely affect anyone who is really experienced, but can provide such a large upside for others.

Adam Johnson

unread,
Aug 16, 2017, 8:08:07 AM8/16/17
to django-d...@googlegroups.com
I wouldn't want is to give free optimisations to non-ORM pros

Something like 99% of django projects are by non-ORM pros, it can be easy to forget that on a mailing list of experts.

On 16 August 2017 at 12:27, Josh Smeaton <josh.s...@gmail.com> wrote:
It won't affect experienced users. They'll read the release notes, see that this change has been implemented, and either go and delete a bunch of prefetch_related() calls, grumble a bit and turn auto-prefetch off globally or just file it away as another fact they know about the Django ORM.

This is, for me, the biggest point in favour of having it opt out. It'll barely affect anyone who is really experienced, but can provide such a large upside for others.

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-developers+unsubscribe@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.



--
Adam

Anssi Kääriäinen

unread,
Aug 16, 2017, 8:14:29 AM8/16/17
to Django developers (Contributions to Django itself)
On Wednesday, August 16, 2017 at 2:27:11 PM UTC+3, Josh Smeaton wrote:
It won't affect experienced users. They'll read the release notes, see that this change has been implemented, and either go and delete a bunch of prefetch_related() calls, grumble a bit and turn auto-prefetch off globally or just file it away as another fact they know about the Django ORM.

This is, for me, the biggest point in favour of having it opt out. It'll barely affect anyone who is really experienced, but can provide such a large upside for others.

There is huge potential for this feature going very bad for performance. For example, this common anti-pattern would immediately cause interesting issues:

if qs:
    qs[0].do_something()

then if do_something() does access a couple of relations, you'll load data for the whole queryset where you only need it for the first one. So, at least make this opt-in instead of opt-out.

Doing this for "select_related" cases on opt-in basis seems like a plausible idea. Doing this for reverse foreign key or m2m cases where you need to use prefetch_related seems complex to implement, and just for that reason I'd avoid the prefetch related case at least initially.

Note that it should be possible to implement this fully as 3rd party project if we add an easy way to customise how related object fetching is done. I'm not sure if we can add an easy way for that.

By the way, a very efficient test for N+1 queries issue is to do something like this:

def test_nplusone_queries(self):
    self.create_object()
    with self.count_queries() as cnt:
        self.client.get('object_listing/')
    self.create_object()
    with self.assertNumQueries(cnt):
        self.client.get('object_listing/')

that is, you test the same list view with one and two objects. If there was an easy way to write tests like this, that would make n+1 queries problems a lot easier to detect. Maybe something to make this kind of test trivial to write could be in Django? Something like self.assertListViewScales(object_creator, 'view_name')?

 - Anssi

Luke Plant

unread,
Aug 16, 2017, 8:48:54 AM8/16/17
to django-d...@googlegroups.com

Hi Josh,


On 16/08/17 02:26, Josh Smeaton wrote:
I believe we should be optimising for the **common** use case, not expecting everyone to be experts with the ORM.

> If I can come up with a single example where it would significantly decrease performance (either memory usage or speed) compared to the default (and I'm sure I can), then I would be strongly opposed to it ever being default behaviour. 

The status quo is already one where thousands of users and sites are doing the non-optimal thing because we're choosing to be conservative and have users opt-in to the optimal behaviour.

I wouldn't say it is "optimal behaviour". It is behaviour that is an optimization for some use cases - common ones, I'd agree - but not all. In fact it is not even the best optimization - it performs less well in many cases than a manual `select_related`.

We don't know how many sites would be affected by the opposite default, because we aren't putting people in that situation. Generating potentially large queries (i.e. ones that return lots of results) is going to make someone's life a lot harder, and can even crash processes (out of memory errors), or cause massive slowdown due to insufficient memory and swapping. I have had these kind of issues in production systems, and sometimes the answer is to prefetch *less* - which is why things like `iterator()` exist, because sometimes you *don't* want to load it all into memory upfront.


A massive complaint against Django is how easy it is for users to build in 1+N behaviour. Django is supposed to abstract the database away (so much so that we avoid SQL related terms in our queryset methods), yet one of the more fundamental concepts such as joins we expect users to know about and optimise for.

This is far from the only place where we expect users to be conscious of what has to go on at the database level. For example, we expect users to use `.count()` and `.exists()` where appropriate, and not use them where not appropriate - see https://docs.djangoproject.com/en/1.11/topics/db/optimization/#don-t-overuse-count-and-exists

This is an example of doing it right. We could have 'intelligently' made `__len__()` do `count()`, but this introduces queries that the user did not ask for, and that's hard for developers to predict. That whole section of the docs on DB optimisation depends on the possibility of understanding things at a DB level, and understanding how QuerySets behave, and that they only do the queries that you ask them to do. The more magic we build in, the harder we make life for people trying to optimize database access.

If we have an `auto_prefetch` method that has to be called explicitly, then we are allowing users who know less about databases to get something that works OK for many situations. But having it on by default makes optimization harder and adds unwelcome surprises.



I'd be more in favour of throwing an error on non-select-related-foreign-key-access than what we're currently doing which is a query for each access.

I have some sympathy with this, but I doubt it is somewhere we can go from the current ORM and Django ecosystem as a default - but see below.



The only options users currently have of monitoring poor behaviour is:

1. Add logging to django.db.models
2. Add django-debug-toolbar
3. Investigate page slow downs

Here's a bunch of ways that previously tuned queries can "go bad":

1. A models `__str__` method is updated to include a related field
2. A template uses a previously unused related field
3. A report uses a previously unused related field
4. A ModelAdmin adds a previously unused related field

I completely agree that visibility of this problem is a major issue, and would really welcome work on improving this, especially in DEBUG mode. One option might be a method that replaces lazy loads with exceptions. This would force you to add the required `prefetch_related` or `select_related` calls. You could have:

.lazy_load(None)   # exception on accessing any non-loaded FK objects

.lazy_load('my_fk1', 'my_fk2')  # exceptions on accessing any unloaded FK objects apart from the named ones

.lazy_load('__any__')   # cancel the above, restore default behaviour

This (or something like it) would be a different way to tackle the problem - just throwing it out. You could have a Meta option to do `.lazy_load(None)` by default for a Model.  I've no idea how practical it would be to wire this all up so that is works correctly, and with nested objects etc.

This would be a bit of a departure from the current ORM, especially if we wanted to migrate to it being the default behaviour. If we are thinking long term, we might have to move to something like this if the future is async. Lazy-loading ORMs are not very friendly to async code, but an ORM where you must specify a set of queries to execute up-front might be more of a possibility.


I think a better question to ask is:

- How many people have had their day/site ruined because we think auto-prefetching is too magical?
- How many people would have their day/site ruined because we think auto-prefetching is the better default?

Answer - we could guess, but we don't know, and we still have problems both way, of different frequencies and size. In this case, I think "explicit is better than implicit" is the wisdom to fall back on. We should also fall back to the experience we've had with this in the past. We did have more magical performance fixes in the past, such as the `depth` argument to `select_related`, removed in 1.7. You now have to explicitly name the things you want to be selected, instead of the 'easy' option which did the wrong thing in some cases.

 

If we were introducing a new ORM, I think the above answer would be obvious given what we know of Django use today.

What I'd propose:

1. (optional) A global setting to disable autoprefetching

This would almost surely interact very badly with 3rd party libraries and apps who will all want you to set it differently.


2. An opt out per queryset
3. (optional) An opt out per Meta?
4. Logging any autoprefetches - perhaps as a warning?

Logging of possible improvements or auto-prefetches could be really helpful. We should be careful to namespace the logging so that it can be silenced easily. The biggest issue with logs/warnings is that the unhelpful reports drown out the helpful ones, and then the whole feature becomes useless or worse.

Regards,

Luke

Marc Tamlyn

unread,
Aug 16, 2017, 9:04:13 AM8/16/17
to django-d...@googlegroups.com
As an opt in feature, it does sound quite interesting. If over the course of a few releases, it proves to be reliable and we don't get tons of support requests of it either not working, or causing the opposite problem, we can consider moving it to an opt out feature. This makes it easy for people to "turn on the magic", but keeps the default safer. It would be very easy to write a one line monkeypatch to make it default behaviour.

Django is conservative when it comes to changes to default behaviour, and doubly so when the ORM is considered. This will need to have been used widely in the wild before it would be considered safe as a default behaviour for all projects. This whole process would only take a couple of years, which isn't much time in Django release land! I don't mean to undermine the belief of the people who think it's definitely an improvement in most cases, I just want us to be cautious in how we explore that hypothesis.

It's also likely to require a significant patch, and need careful analysis before merging. I'd suggest it's a good candidate for a DEP to discuss the motivation for the project, and to find a shepherd from the core team (Josh? Adam?) to help it land.

To unsubscribe from this group and stop receiving emails from it, send an email to django-developers+unsubscribe@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-developers+unsubscribe@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.

Tom Forbes

unread,
Aug 16, 2017, 9:52:59 AM8/16/17
to django-d...@googlegroups.com
Some quicker changes that have been brought up here could be implemented in the interim, like adding intelligent warnings.

Someone brought up a great point about how the ORM hides most SQL terminology from the user, but still requires the knowledge of the difference between prefetch and select related.

Perhaps a good idea would be to create a generic 'related' method on the queryset that handles both cases? Hiding the differences between how m2m and foreign keys are fetched could make them seem less complicated and more approachable to new users? 

Gordon Wrigley

unread,
Aug 16, 2017, 10:33:36 AM8/16/17
to django-d...@googlegroups.com
It's also likely to require a significant patch

The guts of it are actually surprisingly clean and small. That's probably a testament to some of the good decisions in the ORM architecture.
Covering one2one in both directions, FK's in the forward direction, ignoring tests and various optin/out options, it's less than 20 lines, split reasonably evenly between the three *Descriptor.__get__ functions, and QuerySet._fetch_all.
Of course lines of code is not a measure of complexity or risk :)


--
You received this message because you are subscribed to a topic in the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-developers/EplZGj-ejvg/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-developers+unsubscribe@googlegroups.com.

To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.

Brice Parent

unread,
Aug 16, 2017, 12:29:15 PM8/16/17
to django-d...@googlegroups.com
Le 16/08/17 à 14:07, Adam Johnson a écrit :
I wouldn't want is to give free optimisations to non-ORM pros

Something like 99% of django projects are by non-ORM pros, it can be easy to forget that on a mailing list of experts.
I don't count myself as an ORM or SQL expert at all, but I've worked on at least 2 projects for which they had contracted such experts to optimise their projects once they reached some limits. Those experts only worked for them for a limited period of time, and if we changed this behaviour by default, I'm 100% sure they wouldn't understanding why their website was getting slower with the new release. And they would probably only see the performance issue on staging servers if they have some, or in production with a full database.
I admit this can be a great thing for new comers and even small sites. But remember that, with or without this functionality, their website will need to be optimised in many ways when they start to have more users, and removing this 1+N common pitfall (or hiding the problem, as it is not completely solved as it's not the more efficient fix) will not be the only point they should look at.
I think the solution for this would simply be to have it as opt-out, not to harm any already-working and optimised websites and allow to maintain a stable behaviour for 3rd party apps, but make it opt-in to new users just by pre-setting some setting in the settings.py file generated by "django-admin startproject". It could be a simple boolean setting or a list of apps for which we want the auto-fetch feature to be activated on. With this, new projects would be optimised unless they want to optimise manually, existing projects would still work without decreasing performance or creating memory problems in any case. Best of both worlds.
And for existing non-optimised but existing websites, I prefer the status-quo than risking to create problems that might occur on production website.
We could also, as proposed elsewhere in this thread, warn the developers (so only when settings.debug is set) when this kind of 1+N queries are executed that it could be way more efficient, either by activating the auto-fetch functionality or by manually prefetch related data.

- Brice

Tom Evans

unread,
Aug 16, 2017, 12:50:08 PM8/16/17
to django-d...@googlegroups.com
Is this opt-{in,out} considered to be a global flag, meant to be
toggled on or off depending on whether it is an "expert" working on
the project or not?

I don't think that would be a good idea, almost all of our projects
have a mix of skill levels, and people move from team to team on a
regular basis. I don't think we have a project that has only been
worked on by senior developers or only worked on by junior developers.

What I think would be exceptionally useful would be to emit loud
warnings when developing (DEBUG=True or runserver) whenever this code
can detect that a prefetch MAY be applicable. A lot of our junior
developers are not as aware about DB structures and SQL performance
(particularly now that they don't design schemas and write DB
queries), so warnings as part of their normal development help trigger
teaching moments. Magically (sometimes) making things faster doesn't
teach them anything.

Turning this feature on/off per app is scary. If we're dealing with
models from AppA, we will get auto pre-fetching, but if we work with
models from AppB, we do not? If we're dealing with those models in the
same module, we will have different behaviour depending on which model
is being used? Please no.

I also think that it might be handy to specify
"qs.prefetch_related(auto=True)", or "with qs.auto_prefetch():", which
would then trigger the newly proposed behaviour. It's like "I want you
to prefetch all the things I use, but I don't know what just yet".
Having said that, I'd also like that to spit out a warning (again, dev
only) that specified what was actually prefetched, because why waste a
DB query in production to determine what we know whilst developing?

Cheers

Tom
> --
> You received this message because you are subscribed to the Google Groups
> "Django developers (Contributions to Django itself)" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-develop...@googlegroups.com.
> To post to this group, send email to django-d...@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-developers.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-developers/dc483976-f7d0-3aee-4f9e-76f515e5c761%40brice.xyz.

Brice Parent

unread,
Aug 16, 2017, 1:41:47 PM8/16/17
to django-d...@googlegroups.com

Le 16/08/17 à 18:49, 'Tom Evans' via Django developers (Contributions to
Django itself) a écrit :
> Is this opt-{in,out} considered to be a global flag, meant to be
> toggled on or off depending on whether it is an "expert" working on
> the project or not?
>
> I don't think that would be a good idea, almost all of our projects
> have a mix of skill levels, and people move from team to team on a
> regular basis. I don't think we have a project that has only been
> worked on by senior developers or only worked on by junior developers.
I didn't mean to have such a thing activated just for some users and not
for others, which would make no sense. I was speaking about having it on
an entire project level, just for some queries, or not at all. The
project manager being the one chosing whether it is activated or not.
But I was just proposing that because it was, to me, a way to make it
harmless for already optimised cases. If it was just for me, I would
just warn the developers that some improvement could be done, with the
lines numbers and a link to a documentation explaining how to prefetch
efficiently. But if this functionality had to be inserted in Django, I
would prefer it to be opt-in.
>
> What I think would be exceptionally useful would be to emit loud
> warnings when developing (DEBUG=True or runserver) whenever this code
> can detect that a prefetch MAY be applicable. A lot of our junior
> developers are not as aware about DB structures and SQL performance
> (particularly now that they don't design schemas and write DB
> queries), so warnings as part of their normal development help trigger
> teaching moments. Magically (sometimes) making things faster doesn't
> teach them anything.
I totally agree!
>
> Turning this feature on/off per app is scary. If we're dealing with
> models from AppA, we will get auto pre-fetching, but if we work with
> models from AppB, we do not? If we're dealing with those models in the
> same module, we will have different behaviour depending on which model
> is being used? Please no.
I didn't really think about this, it was just an idea to limit the scope
of it, maybe to help 3rd party apps not to become less efficient or
buggy because of it. But again, I'm for empowering the devs with debug
tips and warnings more than making the things for them magically.
>
> I also think that it might be handy to specify
> "qs.prefetch_related(auto=True)", or "with qs.auto_prefetch():", which
> would then trigger the newly proposed behaviour. It's like "I want you
> to prefetch all the things I use, but I don't know what just yet".
> Having said that, I'd also like that to spit out a warning (again, dev
> only) that specified what was actually prefetched, because why waste a
> DB query in production to determine what we know whilst developing?
That's a good idea. The biggest use case for this auto-prefetch thing is
not for backend developers who should be made aware of prefetching, but
for integrators who just use the templating system.
Maybe a message level could be created (named advice, or anything like
that), inheriting from debug so it would be deactivated automatically in
debug=False environments. And when this 1+N querying is found (but
really found, meaning that we are able to confirm that we've queried N
times the db more than needed), it could raise this "advice". This could
easily (I guess) be caught by CI services the same way linters check for
common mistakes in the syntax.

- Brice

Aymeric Augustin

unread,
Aug 16, 2017, 4:17:49 PM8/16/17
to django-d...@googlegroups.com
On 15 Aug 2017, at 11:44, Gordon Wrigley <gordon....@gmail.com> wrote:

I'd like to discuss automatic prefetching in querysets. Specifically automatically doing prefetch_related where needed without the user having to request it.


Hello,

I'm rather sympathetic to this proposal. Figuring out N + 1 problems in the admin or elsewhere gets old.


In addition to everything that was said already, I'd like to point out that Django already has a very similar "magic auto prefetching" behavior in some cases :-)

I'm referring to the admin which calls select_related() on non-nullable foreign keys in the changelist view. The "non-nullable" condition makes that behavior hard to predict — I'd go as far as to call it non deterministic. For details, see slide 54 of https://myks.org/data/20161103-Django_Under_the_Hood-Debugging_Performance.pdf and the audio commentary at https://youtu.be/5fheDDj3oHY?t=2024.


The feature proposed here is most useful if it's opt-out because it targets people who aren't aware that the problem even exists — at best they notice that Django is slow and that reminds them vaguely of a rant that explains why ORMs are the worst thing since object oriented programming.

It should kick in only when no select_related or prefetch_related is in effect, to avoid interfering with pre-existing optimizations. It's still easy to construct an example where it would degrade performance but I don't think such situations will be common in practice. Still, there should be a per-queryset opt-out for these cases.

We may want to introduce it with a deprecation path, that is, make it opt-in at first and log a deprecation warning where the behavior would kick-in, so developers who want to disable it can add the per-queryset opt-out.


At this point, my main concerns are:

1) The difficulty of identifying where the queryset originates, given that querysets are lazy. Passing objects around is common; sometimes it can be hard to figure out where an object comes from. It isn't visible in the stack trace. In my opinion this is the strongest argument against the feature.

2) The lack of this feature for reverse one-to-one relations; it's only implemented for foreign keys. It's hard to tell them apart in Python code. The subtle differences, like return None vs. raise ObjectDoesNotExist when there's no related object, degrade the developer experience.

3) The strong opinions expressed against the feature. I'm not sure that consensus is within reach. If we can't agree that this is an adequate amount of magic, we're likely to stick with the status quo. I'd rather not have this question decided by a vote of the technical board.


In the grand scheme of things, going from "prefetching a related instance for an object" to "prefetching related instances for all objects in the queryset" isn't that much of a stretch... But I admit it's rather scary to make this change for all existing Django projects!


Best regards,

-- 
Aymeric.




Gordon Wrigley

unread,
Aug 16, 2017, 5:07:01 PM8/16/17
to django-d...@googlegroups.com
Regarding 2, it does work for reverse one-to-one relations.

--
You received this message because you are subscribed to a topic in the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-developers/EplZGj-ejvg/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-developers+unsubscribe@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.

Shai Berger

unread,
Aug 16, 2017, 7:34:03 PM8/16/17
to django-d...@googlegroups.com
First of all, I think making the auto-prefetch feature available in some form
is a great idea. As an opt-in, I would have made use of it on several
occasions, and cut days of optimization work to minutes. It's true that this
wouldn't achieve the best possible optimization in many cases, but it would be
close enough, for a small fraction of the effort.

But of the choices that have been suggested here, I find none quite
satisfactory. I agree, basically, with almost all of the objections raised on
all sides. And I think I have a better suggestion.

Rather than a setting (global and essentially constant) or all-local opt-ins,
suppose the feature was controlled -- for all querysets -- by a context
manager.

So, rather than

> "qs.prefetch_related(auto=True)", or "with qs.auto_prefetch():",

suppose we had

with QuerySet.auto_prefetch(active=True):

and under that, all querysets would auto-prefetch. Then:

- We could put that in a middleware; using that middleware would then,
effectively, be a global opt in. We could add the middleware -- perhaps
commented-out -- to the new project template, for beginner's sake. Call it
PerformanceTrainingWheelsMiddleware, to make people aware that it's something
they should grow out of, but make it easily accessible.

- We could easily build a decorator for views

- We could have local opt-out, at the correct level -- not the objects, but
the control flow.

For this to work, the flag controlling the feature would need to be thread-
local and managed as a stack. But these aren't problems.

If (as likely) this suggestion still does not generate a concensus, I would
prefer that we follow the path Anssi suggested --

> Note that it should be possible to implement this fully as 3rd party
> project if we add an easy way to customise how related object fetching is
> done. I'm not sure if we can add an easy way for that.

Except I don't think "easy" is a requirement here. If we can add a sensible
way, that would be enough -- I don't expect many Django users to develop
implementations of the feature, only to use them.

My 2 cents,
Shai.

Josh Smeaton

unread,
Aug 16, 2017, 7:42:28 PM8/16/17
to Django developers (Contributions to Django itself)
I think there's a lot right with your suggestions here Shai. 

It delivers better default behaviour for new projects, does not affect existing deployments, and seems pretty easy to enable/disable selectively at any level of the stack.

My only concern would be libraries leaning on this behaviour by enabling it locally and users being unable to change it. That's only a small concern though, and wouldn't prevent me from recommending the proposal.

Gordon Wrigley

unread,
Aug 17, 2017, 2:57:19 AM8/17/17
to django-d...@googlegroups.com
I'm not advocating either way on this, but it's probably worth noting that the context manager proposal is compatible with a queryset level optin/out and an object level optout.

So you could for example have prefetch_related(auto=None) which can be explicitly set to True / False and takes it's value from the context manager when it's None.


--
You received this message because you are subscribed to a topic in the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-developers/EplZGj-ejvg/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-developers+unsubscribe@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.

Malcolm Box

unread,
Aug 17, 2017, 5:02:39 AM8/17/17
to Django developers (Contributions to Django itself)
Hi,

I think there's a potential to make this opt-in, and improve the out-of-box experience.

Summarising the discussion, it seems that the rough consensus is that if we were building the ORM from scratch, then this would be entirely sensible behaviour (with necessary per-QS ways to disable) - it would remove a common performance problem (N+1 queries), would improve areas where adding prefetch_related to queries is awkward, and in rare cases where it decreased performance there would be documented ways to fix.

So the main disagreement is about how to get there from here, and there's concern about three types of users:

1 - Existing, non-expert users whose sites work now (because otherwise they would have already fixed the problem) but who have lurking N+1 issues which will break them later
2 - Existing, non-expert users whose sites work now, but would have performance issues if this was enabled by an upgrade
3 - Existing, expert users who have already found and fixed the issues and who could therefore get no benefit but might suffer a performance degradation.

I'll assert that the size of these populations above is listed in roughly size order, with #1 being the biggest. This is a hunch based on most sites not having huge tables where N+1 becomes a problem - at least not until they've been running for a few years and accumulated lots of data...

There is another population that hasn't been considered - users starting django projects (ie people running django-admin startproject). Over time, this is by far the largest population. 

So would a sensible approach be:

- Feature is globally opt-in 
- startproject opts in for new projects
- Release notes mention the new flag loudly, and encourage people to try switching it on
- We add the debug tracing to help people find places where this setting would help - and encourage them to enable it globally before trying individual queryset.prefetch_related

Then over time, all new projects will have the new behaviour. Old projects will gradually upgrade - everyone in category 1 will hit the "make it work" switch the first time they see the warning / see a problem. Experts can choose how they migrate - as Adam points out, even experts can miss things.

Finally after a suitable warning period, this can become an opt-out feature and we arrive in the sunny world of an ORM that works better for all users.

Cheers,

Malcolm

Andrew Godwin

unread,
Aug 17, 2017, 1:34:00 PM8/17/17
to Django developers (Contributions to Django itself)
Just some quick thoughts, as most of the points I would bring up have been discussed:

- This should definitely be opt-in for the first release, it's too big a change to make opt-out straight away.

- You should be able to turn it on/off per model, probably in Meta, not in a setting, and obviously be able to override it on the queryset level

- I am concerned for the nasty performance edge cases this will cause with single-object access patterns (like Anssi's example), but I think the overall gain would likely be worth it.

In general, very large sites won't be able to use this at all as JOINs or cross-table queries in one piece of code aren't allowed, but they probably already have plenty of expertise in this area. We also need to give consideration to how it will interact with multiple database support, and third-party solutions to things like sharding.

Andrew

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-developers+unsubscribe@googlegroups.com.

To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.

Collin Anderson

unread,
Aug 17, 2017, 2:10:10 PM8/17/17
to django-d...@googlegroups.com
"turn it on/off per model" - I wonder if we just have a custom manager/mixin for the per model case. objects = AutoPrefetchRelatedManager(). The manager can return a queryset with prefetch_related(auto=True) or whatever already applied.

Aymeric Augustin

unread,
Aug 17, 2017, 4:30:45 PM8/17/17
to django-d...@googlegroups.com
Hello,

> On 17 Aug 2017, at 14:48, Luke Plant <L.Pla...@cantab.net> wrote:
>
> On 16/08/17 23:17, Aymeric Augustin wrote:
>> It should kick in only when no select_related or prefetch_related is in effect, to avoid interfering with pre-existing optimizations. It's still easy to construct an example where it would degrade performance but I don't think such situations will be common in practice.
>
> I think Ansii's example is a non-contrived and potentially very common one where we will make things worse if this is default behaviour, especially for the non-expert programmer this behaviour is supposed to help:
>
>
> if qs:
> qs[0].do_something()
>
> (where do_something() access relations, or multiple relations). We will end up with *multiple* large unnecessary queries instead of just one. The difference is that the first one is easy to explain, the remainder are much harder, and will contribute even more to the "Django is slow/ORMs are bad" feeling.


I wasn't convinced by this example because it's already sub-optimal currently. `if qs` will fetch the whole queryset just to check if it has at least one element.

Assuming there's 1000 elements in qs, if you don't care about a 1000x inefficiency, I don't expect you to care much about two or three 1000x inefficiencies...

--
Aymeric.


Anssi Kääriäinen

unread,
Aug 18, 2017, 2:08:11 AM8/18/17
to Django developers (Contributions to Django itself)
I agree that this example isn't particularly worrying. It's something an experienced developer wouldn't do. On the other hand, we are aiming at making things simpler for non-experienced developers.

To me the worrying part here is that we really don't have any data or experience about if the cure will be worse than the disease. Likely not, but what do we gain by taking risks here?

Maybe we should just add the queryset method. This is the smallest atomic task that can be done. Even if there's only the queryset method available, it's possible to enable prefetches per model by using a Manager.

 - Anssi


Shai Berger

unread,
Aug 18, 2017, 7:01:33 AM8/18/17
to django-d...@googlegroups.com
On Friday 18 August 2017 09:08:11 Anssi Kääriäinen wrote:
> Maybe we should just add the queryset method. This is the smallest atomic
> task that can be done. Even if there's only the queryset method available,
> it's possible to enable prefetches per model by using a Manager.
>
I disagree on both counts: I don't think it's the smallest atomic task, and
I'm not so sure it's the right thing to do.

The smallest atomic task, the way I see it, is building the infrastructure
that would allow adding the queryset method -- but would also allow different
APIs to be set around it.

And since there is as yet no consensus on the correct API for "end" users, I
would rather not define one immediately.

Shai.

Collin Anderson

unread,
Aug 18, 2017, 8:06:30 AM8/18/17
to django-d...@googlegroups.com
I like that idea - keep it a private API for now and make it a public API once people have used it a little bit.

Todor Velichkov

unread,
Aug 19, 2017, 5:09:14 AM8/19/17
to Django developers (Contributions to Django itself)
+1 to just add the queryset method it gives a fine granular level of control. Moreover when not used we could display warnings which can help people detect these O(n) query cases as Tom Forbes initially suggested.

Luke Plant

unread,
Aug 19, 2017, 1:11:07 PM8/19/17
to django-d...@googlegroups.com

This could work something like the way that ForeignKey `on_delete` works - you have options that are enumerated as constants, but in reality they are classes that embody the strategy to be used. We could have something similar - `on_missing_relation=FETCH | WARN | ERROR | IGNORE ... `

Luke

Tobias McNulty

unread,
Aug 21, 2017, 11:45:12 AM8/21/17
to django-developers
On Sat, Aug 19, 2017 at 1:10 PM, Luke Plant <L.Pla...@cantab.net> wrote:

This could work something like the way that ForeignKey `on_delete` works - you have options that are enumerated as constants, but in reality they are classes that embody the strategy to be used. We could have something similar - `on_missing_relation=FETCH | WARN | ERROR | IGNORE ... `

I like this a lot. It (1) caters (I think) to many if not all of the behavior preferences expressed in this thread, (2) mimics an existing API we support, (3) allows projects to gradually add/try the feature, and (4) permits but does not require a deprecation path for changing the default behavior in the future. I'm assuming `FETCH` represents the current behavior and not auto-detection of a missing relation and modification of the associated QuerySet.

One alternative thought: Could we define two `ForeignKey` options (again using the `on_delete` analogy) which support adding the relation to select_related()/prefetch_related() all the time (e.g., `ForeignKey(prefetch_related=ALWAYS | MANUALLY | WARN | ERROR)` and/or `ForeignKey(select_related=ALWAYS | MANUALLY | WARN | ERROR)`, where MANUALLY represents the current behavior)? One could then use `.only()` or `.values*()` to avoid fetching the related model, if needed.

Tobias McNulty
Chief Executive Officer

tob...@caktusgroup.com
www.caktusgroup.com




Shai Berger

unread,
Aug 21, 2017, 8:12:57 PM8/21/17
to django-d...@googlegroups.com
On Monday 21 August 2017 18:44:35 Tobias McNulty wrote:
> On Sat, Aug 19, 2017 at 1:10 PM, Luke Plant <L.Pla...@cantab.net> wrote:
> > This could work something like the way that ForeignKey `on_delete` works
> > - you have options that are enumerated as constants, but in reality they
> > are classes that embody the strategy to be used. We could have something
> > similar - `on_missing_relation=FETCH | WARN | ERROR | IGNORE ... `
>
> I like this a lot. It (1) caters (I think) to many if not all of the
> behavior preferences expressed in this thread, (2) mimics an existing API
> we support, (3) allows projects to gradually add/try the feature, and (4)
> permits but does not require a deprecation path for changing the default
> behavior in the future. I'm assuming `FETCH` represents the current
> behavior and not auto-detection of a missing relation and modification of
> the associated QuerySet.
>

I agree that the idea sounds nice, with one exception: It seems like this
would make sense, mostly, at the foreign-key-definition level, which means the
feature is applied at model scope -- altough it isn't quite clear. However,
the main argument so far was exactly about the right scope to use, with four
different suggestions as far as I could see (queryset, model, context-manager
and a global setting), each with its own pros and cons. So, it feels a little
like going off the main thread of discussion.

> One alternative thought: Could we define two `ForeignKey` options (again
> using the `on_delete` analogy) which support adding the relation to
> select_related()/prefetch_related() all the time (e.g.,
> `ForeignKey(prefetch_related=ALWAYS | MANUALLY | WARN | ERROR)` and/or
> `ForeignKey(select_related=ALWAYS | MANUALLY | WARN | ERROR)`, where
> MANUALLY represents the current behavior)? One could then use `.only()` or
> `.values*()` to avoid fetching the related model, if needed.
>

This is truly, clearly off-topic here; I just want to point out that the effect
can already be achieved by overriding the model's default manager's
get_queryset(). The idea might have merits in terms of maintainability and
readability, but I'd much rather it be discussed separately.

Shai

Patryk Zawadzki

unread,
Aug 30, 2017, 5:15:17 AM8/30/17
to Django developers (Contributions to Django itself)
W dniu środa, 16 sierpnia 2017 14:48:54 UTC+2 użytkownik Luke Plant napisał:

I completely agree that visibility of this problem is a major issue, and would really welcome work on improving this, especially in DEBUG mode. One option might be a method that replaces lazy loads with exceptions. This would force you to add the required `prefetch_related` or `select_related` calls. You could have:


.lazy_load(None)   # exception on accessing any non-loaded FK objects

.lazy_load('my_fk1', 'my_fk2')  # exceptions on accessing any unloaded FK objects apart from the named ones

.lazy_load('__any__')   # cancel the above, restore default behaviour

This (or something like it) would be a different way to tackle the problem - just throwing it out. You could have a Meta option to do `.lazy_load(None)` by default for a Model.  I've no idea how practical it would be to wire this all up so that is works correctly, and with nested objects etc.

Would love if Django could be told to require explicit data fetches. This and replacing QuerySet.__iter__ with an explicit fetch() (and lazy_fetch()) would make it much easier to reason about large codebases.

Gordon Wrigley

unread,
Sep 12, 2017, 12:28:08 PM9/12/17
to django-d...@googlegroups.com
This received some positive responses, so to help move the conversation along I have created a ticket and pull request.


Regards G

On Tue, Aug 15, 2017 at 10:44 AM, Gordon Wrigley <gordon....@gmail.com> wrote:
I'd like to discuss automatic prefetching in querysets. Specifically automatically doing prefetch_related where needed without the user having to request it.

--
You received this message because you are subscribed to a topic in the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-developers/EplZGj-ejvg/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-developers+unsubscribe@googlegroups.com.

To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.

Emil Stenström

unread,
Sep 17, 2017, 2:51:07 AM9/17/17
to Django developers (Contributions to Django itself)
I find it interesting that Gordon ran Django's test suite with this enabled and found examples where tests where doing exactly the kind of this fixes: https://code.djangoproject.com/ticket/28586#comment:4 - I count this as another real-world example where this change helps.

I would definitely be interested in using this in our 7 year old monolith and see if it finds more optimizations we've missed. I'm guessing 10-20 views will magically get faster as this is enabled.

/E
To unsubscribe from this group and all its topics, send an email to django-develop...@googlegroups.com.
To post to this group, send email to django-d...@googlegroups.com.

Gordon Wrigley

unread,
Mar 25, 2020, 6:40:13 AM3/25/20
to Django developers (Contributions to Django itself)
My existing code for this is now available as a pypi package
https://github.com/tolomea/django-auto-prefetch 
Reply all
Reply to author
Forward
0 new messages