[Django]-List of Django model instance foreign keys losing consistency during state changes

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.

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.

0👍

I’ve found a good answer to a similar question, take a look here:

Django Models: preserve object identity over foreign-key following

Leave a comment