【问题标题】:Django subclassing UserProfile problemDjango子类化UserProfile问题
【发布时间】:2011-07-07 10:26:57
【问题描述】:

给定代码:

from django.contrib.auth.models import User

class UserProfile(models.Model):
    # project userprofile, also set as AUTH_PROFILE_MODULE
    user = models.ForeignKey(User, unique=True)

class AppUserProfile(UserProfile):
    # some app specific extension

和测试:

user = User.objects.create()
profile = UserProfile.objects.get_or_create(user=user)
AppUserProfile.objects.create(user=user)

它在最后一行失败,说:

IntegrityError: column user_id is not unique

我怀疑 Django 对由 ForeignKey 定义的 user-userprofile 和 user-anotheruserprofile 关系使用同一个表。

我该如何解决这个问题?

【问题讨论】:

    标签: database django django-models


    【解决方案1】:

    错误的原因是您正在创建两个具有相同 user_id 的 UserProfile-s。您正在使用“多表继承”,因此您只需调用 AppUserProfile.objects.get_or_create(user=user) 即可按预期工作。

    Django Models 的文档解释得很好。

    【讨论】:

    • 谢谢!好的,我明白了这个问题,但我会这样问:如果我有 UserProfile(来自 request.user.get_profile),我怎样才能到达 AppUserProfile 对象)从是吗?
    • 我正在搜索的内容未实现:code.djangoproject.com/ticket/7623
    • 如果我正确理解文档,它应该可以作为 UserProfile 实例的属性使用,在您的情况下为 profile.appuserprofile。
    • 只有当 appuserprofile 是在 userprofile 之前创建时才成立。通过测试学习。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 2015-02-14
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多