Django中的继承:子类用空字段更新父类

2024-10-03 19:20:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为创建的每个用户创建一个UserProfiledjango.contrib.auth公司通过扩展基本抽象用户并在注册新用户时捕获信号(我更喜欢为概要文件创建单独的表):

class UserProfile(auth_models.User):
    objects = UserProfileManager()
    organization = models.CharField(max_length=100)
    country = CountryField()
    is_verified = models.BooleanField(default=False)
    blocked = models.BooleanField(default=False)
    anonymous = models.BooleanField(default=False)

@django_dispatch.receiver(
    django_signals.post_save, sender=auth_models.User
)
def user_migrated(sender, instance, created, raw, **kwargs):
    if not created or raw:
        return
    if instance.pk != 1:
        return
    account_models.UserProfile.objects.create(
        user_ptr=instance,
        organization='The SATNet Network',
        country='US'
    )

问题是,每次创建用户时,基本用户首先被正确插入,但是创建概要文件会促使Django“更新”刚刚用空值创建的基本用户:

^{pr2}$

如果我没有创建概要文件,那么用户将被正确插入,因为Django不会更新模型:

DEBUG (0.001) INSERT INTO "auth_user" ("password", "last_login", "is_superuser", "username", "first_name", "last_name", "email", "is_staff", "is_active", "date_joined") VALUES ('pbkdf2_sha256$15000$nxWaMTdYVVKO$MGWYHw/NXoEwCxBryK+bYOoqTYsO0DXgyqkBEQNxq/I=', '2015-06-02 18:53:54.716366+00:00', true, 'satnet_admin', '', '', 'satnet.calpoly@gmail.com', true, true, '2015-06-02 18:53:54.716366+00:00') RETURNING "auth_user"."id"; args=('pbkdf2_sha256$15000$nxWaMTdYVVKO$MGWYHw/NXoEwCxBryK+bYOoqTYsO0DXgyqkBEQNxq/I=', '2015-06-02 18:53:54.716366+00:00', True, 'satnet_admin', '', '', 'satnet.calpoly@gmail.com', True, True, '2015-06-02 18:53:54.716366+00:00')
Superuser created successfully.

正确的处理方法是什么?Django总是这样更新模型还是我遗漏了什么?在

环境:Python 3.4.2+Django 1.7.4+PostgreSQL)


Tags: djangoinstance用户authfalsetruedefaultis
1条回答
网友
1楼 · 发布于 2024-10-03 19:20:05

我怀疑问题是您继承了auth_models.User。这是多表继承,并不适合这种情况。请参阅以下django文档:https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#extending-django-s-default-user

也就是说,如果您想在单独的表中存储配置文件数据,则不需要扩展auth_models.User。只需创建一个带有OneToOneFieldauth_models.User的模型:

class UserProfile(models.Model):
    objects = UserProfileManager()
    organization = models.CharField(max_length=100)
    country = CountryField()
    is_verified = models.BooleanField(default=False)
    blocked = models.BooleanField(default=False)
    anonymous = models.BooleanField(default=False)
    user = models.OneToOneField(auth_models.User)

相关问题 更多 >