2👍
This is because, as far as I can tell, there’s no global cache of model instances, so each query creates new instances, and your lists of related objcts are created lazily using separate queries.
You might find that select_related() is smart enough to solve the problem in this case. Instead of code like:
match = Match.objects.filter(...).get()
use:
match = Match.objects.select_related().filter(...).get()
That creates all the attribute instances at once and may be smart enough to re-use instances. Otherwise, you are going to need some kind of explicit cache (which is what your solution does).
Warning: I am surprised by this kind of behaviour myself and am not an expert on this. I found this post while searching for information on this kind of issue in my own code. I’m just sharing what I think is happening as I try to understand…
1👍
You might want to check out django-idmapper It defines a SharedMemoryModel so that there is only one copy of each instance in the interpreter.
- [Django]-Displaying the last object of nested relationship
- [Django]-How to use custom django templatetag with django template if statement?
0👍
Uh, are you using get_or_create() for the Player records? If not, then you are probably creating new instances of identical (or near identical) Player records on every match. This can lead to tears and/or insanity.
- [Django]-Django CharFIeld with unique=True update error "Instance with this Name already exists"
- [Django]-How to make certain that the queryset will be ordered by a valid field – django
0👍
I’ve found a good answer to a similar question, take a look here:
Django Models: preserve object identity over foreign-key following
- [Django]-Django auto_add_now not working
- [Django]-Factory boy error : ValueError: save() prohibited to prevent data loss due to unsaved related object
- [Django]-NoReverseMatch in django production server
- [Django]-Send a message from a celery background task to the browser with Django Channels