3

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.

4

1 回答 1

0

关键是要了解您的查询何时实际执行。每次您要访问其模型字段之一时,模型对象都不会重复查询。

为了避免在对象周围保留陈旧数据,我会确保在我真正需要数据时进行查询。在您的示例中,我会保留您知道不会更改的信息( pk 值),并在您需要具有新值的对象时执行 get 。

from myapp import models
models.BagOfApples().save()

bag1 = models.BagOfApples.objects.get(pk = 1)

bag1.quantity += 1
bag1.save()

print bag1.quantity  # will print 1

bag2 = models.BagOfApples.objects.get(pk = 1)
print bag2.quantity  # will print 1 too
于 2013-08-20T17:28:09.053 回答