开发者

Django subclassing UserProfile problem

开发者 https://www.devze.com 2023-02-14 14:52 出处:网络
Given the code: from django.contrib.auth.models import User class UserProfile(models.Model): # project userprofile, also set as AUTH_PROFILE_MODULE

Given the code:

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

and the test:

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

it fails on the last line, saying:

IntegrityError: column user_id is not unique

What I suspect is that Django uses the same table for user-userprofile and user-anotheruserprofile relationship defined by ForeignKey.

How can I solve this problem?


The cause of the error is the fact that you are creating two UserProfile-s with the same user_id. You are using "multi-table inheritance", so you only have to call AppUserProfile.objects.get_or_create(user=user) and it will work as expected.

Documentation for Django Models explains it pretty good.

0

精彩评论

暂无评论...
验证码 换一张
取 消