Last active
December 16, 2015 02:29
-
-
Save AndrewIngram/5362941 to your computer and use it in GitHub Desktop.
prefetch_related makes me sad
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
In : from onefinestay.geo.models import Place | |
In : p = Place.objects.prefetch_related('categories').get(id=1460) # Only prefetching categories | |
In : p.categories.all() | |
Out: [<Category: Miscellaneous>, <Category: For kids>] | |
In : p.regions.all() | |
Out: [<Region: Belgravia>, <Region: Bloomsbury>, <Region: Clerkenwell>, <Region: City of London>] | |
In : p.regions.clear() | |
In : p.regions.all() | |
Out: [] | |
In : p.categories.clear() | |
In : p.categories.all() | |
Out: [<Category: Miscellaneous>, <Category: For kids>] # <---- Booooooooo |
The same as p.regions.clear(). It's deleting all the place->category m2m models:
https://github.com/django/django/blob/master/django/db/models/fields/related.py#L708-L725
I'm pretty sure it's not working because the prefetch_related code isn't smart enough to detect when the .all() queryset would have actually changed.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Did you do any investigation on this? What is that p.categories.clear() is really doing?