Django:使用配置文件onetoonefield错误扩展用户模型

时间:2017-02-23 15:17:50

标签: django django-models

我有这个模型

from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

from my_app.models import Teams

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    team = models.ForeignKey(Teams, on_delete=models.CASCADE)

    class Meta:
        app_label = 'my_app'

    def __str__(self):
        return self.name

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

然后我进入shell

from django.contrib.auth.models import User

当我输入

user = User.objects.create_user(username='test', email='dummyemail@dum.com', password='test')

我不出所料地得到了

IntegrityError: NOT NULL constraint failed: my_app_profile.team_id

但是当我输入

user = User.objects.create_user(username='test', email='dummyemail@dum.com', password='test', team='developer')

我得到了

TypeError: 'team' is an invalid keyword argument for this function

如果我输入

user = User.objects.create_user(username='test', email='dummyemail@dum.com', password='test', profile.team='developer')

我得到了

SyntaxError: keyword can't be an expression

非常感谢任何帮助,提示或指导

1 个答案:

答案 0 :(得分:1)

您还没有允许团队为空,因此当您创建如此的配置文件时:

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        # Team isn't defined
        Profile.objects.create(user=instance)

您将收到错误。

允许团队为空(或在上面的代码中设置默认值):

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    team = models.ForeignKey(Teams, on_delete=models.CASCADE, null=True)

    class Meta:
        app_label = 'my_app'

    def __str__(self):
        return self.name