I have the following models.py
:
class BagOfApples(models.Model):
quantity = models.PositiveSmallIntegerField(default = 0)
Let's create a “bag of apples” object and put an “apple” in it:
>>> from myapp import models
>>>
>>> models.BagOfApples().save()
>>>
>>> bag1 = models.BagOfApples.objects.get(pk = 1)
>>> bag2 = models.BagOfApples.objects.get(pk = 1)
>>>
>>> bag1.quantity += 1
>>> bag1.save()
>>>
>>> bag1.quantity
1
>>> bag2.quantity
0
Is there a way to automatically reload the data in the bag2
variable?
In my real-world application, things are a bit more complicated than that, and the same objects can be modified in different parts of the code after being retrieved by different database queries. This is not even intentional (for instance, this problem occurs to me because Django caches results for OneToOne or ForeignKey relationships).
It would be really helpful to have some kind of manager (maybe a middleware can do this?) that keeps track of the identical objects.
In this example, the manager would automatically detect that bag2
is actually bag1
, and would not execute a second query but simply return bag1
.
If there is no good way to do this, any other helpful tips on better application design would be appreciated.