【问题标题】:Why do Django model-fields get out of sync when traversing relationships?为什么 Django 模型字段在遍历关系时会不同步?
【发布时间】:2011-04-25 23:16:56
【问题描述】:

我在访问已更改的模型字段、遍历 Django 1.3 应用程序中的关系时遇到了问题。提交给数据库的更改不会被内存中的对象反映。我正在使用来自 Auth Middleware 的 User() 对象,将其链接到自定义 Profile() 对象:

User() <---one-to-one---> Profile()

访问 User() 的 email 字段时出现问题:

$ python manage.py shell
>>> from django.contrib.auth.models import User
>>> from myproject.myapp.models import Profile
>>>
>>> user = User.objects.get(pk=1)
>>> profile = user.profile
>>> user.email
u'old@example.com'                  # OK.
>>> profile.user.email
u'old@example.com'                  # OK.
>>> 
>>> user.email = 'new@example.com'  # 1) Changes email address.
>>> user.save()                     # 2) Commits to database.
>>> user.email
'new@example.com'                   # 3) Changes reflected in user.email. Good.
>>> profile.user.email
u'old@example.com'                  # 4) Wrong. This is the old incorrect email.
>>> user.profile.user.email
u'old@example.com'                  # 5) Also wrong.
>>> 
>>> profile = Profile.objects.get(user=user)
>>> profile.user.email
u'new@example.com'                  # 6) If we re-query the DB, things are OK.

为什么在第 4 步和第 5 步中事情会不同步?我对 #5 感到困惑,从保存的用户对象到配置文件,然后返回到同一个保存的用户对象。

显然正在进行某种缓存,但我不确定其背后的逻辑/算法。任何人都知道发生了什么,以及在代码中解决这个问题的最佳方法?感谢您提供的任何见解! :)

【问题讨论】:

    标签: django orm django-models


    【解决方案1】:

    SingleRelatedObjectDescriptor 描述符负责透明地查找相关对象,检查模型实例中 _&lt;fieldname&gt;_cache 中相关对象的缓存版本,并在第一次检索时对其进行缓存。

    Django 的 ORM 不使用身份映射,因此对一个 Model 实例的更改不会自动反映在现有引用所在的其他实例中。

    【讨论】:

    • 啊,有趣。有没有办法强制它使用未缓存的版本?或者我必须从一个新的 QuerySet 中获取它(在我的示例中为 #6)?
    • 同样的问题...重新查询很简单,但是如果有某种 refresh() 方法,那也很好
    • 同意,这样的方法会很方便,但重新查询很容易。 FYI, here is the corresponding feature request.
    【解决方案2】:

    profile.user 不是 user。您正在查看的是 Django 的 ORM 之前从数据库中提取的模型的另一个缓存副本。如果您绝对必须有最新的值,那么您每次都需要重新查询。

    【讨论】:

      猜你喜欢
      • 2011-03-10
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 1970-01-01
      • 2010-11-11
      相关资源
      最近更新 更多