(编辑:我知道 Django 中有一个完全独立的功能,称为“代理模型”。该功能对我没有帮助,因为我需要能够向 UserProfile 添加字段。)
所以我开始一个新的 Django 应用程序,我正在创建一个 UserProfile 模型,它是 django.contrib.auth.models.User 的扩展,并将失败的属性请求返回给用户,如下所示:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
def __getattr__(self, name, *args):
if name == 'user' or name == '_user_cache':
raise AttributeError(name)
try:
return getattr(self.user, name, *args)
except AttributeError, e:
raise AttributeError(name)
这通常可以正常工作,但是当我尝试使用User
UserProfileAdmin.list_display 中的字段时会中断。问题出在此处的管理员验证代码中:
def validate(cls, model):
"""
Does basic ModelAdmin option validation. Calls custom validation
classmethod in the end if it is provided in cls. The signature of the
custom validation classmethod should be: def validate(cls, model).
"""
# Before we can introspect models, they need to be fully loaded so that
# inter-relations are set up correctly. We force that here.
models.get_apps()
opts = model._meta
validate_base(cls, model)
# list_display
if hasattr(cls, 'list_display'):
check_isseq(cls, 'list_display', cls.list_display)
for idx, field in enumerate(cls.list_display):
if not callable(field):
if not hasattr(cls, field):
if not hasattr(model, field):
try:
opts.get_field(field)
except models.FieldDoesNotExist:
raise ImproperlyConfigured("%s.list_display[%d], %r is not a callable or an attribute of %r or found in the model %r."
% (cls.__name__, idx, field, cls.__name__, model._meta.object_name))
问题在于,虽然 UserProfile 的实例将具有代理字段,例如电子邮件,但 UserProfile 类本身却没有。在 Django shell 中演示:
>>> hasattr(UserProfile, 'email')
False
>>> hasattr(UserProfile.objects.all()[0], 'email')
True
经过一番挖掘,看起来我想为 UserProfile._meta 覆盖 django.db.models.options.Options.get_field。但似乎没有一种非 hacky 的方式来做到这一点(我现在有一个非常 hacky 的解决方案,其中涉及猴子修补 UserProfile._meta.[get_field, get_field_by_name])......有什么建议吗?谢谢。