【发布时间】: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