我有一个这样的模型结构:
app1.models
class App(FunkyClassLoadoerMixin, DateMixin):
user = models.OneToOneField(User, blank=False, null=False, db_index=True, unique=True)
# some other fields
class DateMixin(models.Model):
date_added = models.DateTimeField(auto_now_add=True)
app2.models
from app1.models import App as BaseApp
class App(BaseApp)
class Meta:
proxy = True
FunkyClassLoadoerMixin 只是一个有助于以稍微不同的方式加载子类的类,但它不会影响它们的行为。
鉴于此,我有一个类似的查询:
q = SuperStatic.objects.all().select_related('user__app')
(在这种情况下,app 对象的类型应该是 app2.models.App)
当它被评估时,我收到了这个错误:
local/lib/python2.7/site-packages/django/db/models/query.pyc in get_cached_row(row, index_start, using, klass_info, offset)
1435 for rel_field, rel_model in rel_obj._meta.get_fields_with_model():
1436 if rel_model is not None:
-> 1437 setattr(rel_obj, rel_field.attname, getattr(obj, rel_field.attname))
1438 # populate the field cache for any related object
1439 # that has already been retrieved
AttributeError: 'User' object has no attribute 'date_added'
我不太确定为什么会这样。我查看了 Django 源代码,原因似乎是这个函数:
rel_obj._meta.get_fields_with_model()
当模型是子类并忽略它是代理模型的事实时,行为会有所不同。
我找到了一些相关的帖子:
- https://code.djangoproject.com/ticket/10955
- http://python.6.x6.nabble.com/Django-17876-get-klass-info-should-handle-proxy-models-and-with-select-related-td4569828.html
但也没有太大帮助。
关于如何使用代理类并避免此错误的任何想法?