1

(编辑:我知道 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)

这通常可以正常工作,但是当我尝试使用UserUserProfileAdmin.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])......有什么建议吗?谢谢。

4

3 回答 3

2

把事情简单化。这是我们使用的库中的 UserProfile 模型的示例:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    accountcode = models.PositiveIntegerField(null=True, blank=True)

而已。不要为__getattr__覆盖而烦恼。改为自定义管理界面:

from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

class UserProfileInline(admin.StackedInline):
    model = UserProfile

class StaffAdmin(UserAdmin):
    inlines = [UserProfileInline]
    # provide further customisations here

admin.site.register(User, StaffAdmin)

这允许您对User对象进行 CRUD,并将 UserProfile 作为内联访问。现在您不必将来自 UserProfile 的属性查找代理到 User 模型。UserProfile要从的实例访问User u,请使用u.get_profile()

于 2011-03-06T05:45:58.100 回答
0

如果您只想将 User 的字段显示在 UserProfileAdmin 的 list_display 中,请尝试:

class UserProfileAdmin(admin.ModelAdmin):
    list_display = ('user__email',)

如果您想将其作为表单的一部分,请将其作为额外字段添加到您的 UserProfileForm 中,并在表单中对其进行验证。

于 2011-03-06T05:14:15.400 回答
0

这不是代理类,它是一种关系。查看更多关于Proxy Model的信息,它是原始模型的子类,带有Meta.proxy = True

于 2011-03-06T02:03:19.983 回答