我想用以下内容扩展User模型:
class Client(models.Model):
business_name = models.CharField(max_length=128)
category = models.ForeignKey(Category) # the beginning of the problem
user = models.ForeignKey(User, unique=True)
class Category(models.Model):
category = models.CharField(max_length=75)
#the problem is here
def create_client_profile(sender, instance, created, **kwargs):
if created:
Client.objects.create(user=instance)
post_save.connect(create_client_profile, sender=User)
因此,当我尝试同步数据库时,它抱怨category_id不能为null,问题的根源是“create_client_profile”。我怎么解决这个问题? 如果我删除“create_client_profile”它可以工作,但是我会松开get_profile()。
您如何看待this作为解决方案?我不确定它是否足够Djangoish:)
答案 0 :(得分:0)
数据库是否已包含Client
的数据?可能存在null
类别的条目。
如果您将category
中的Client
行更改为:
category = models.ForeignKey(Category, null=True)
有帮助吗?
答案 1 :(得分:0)
因此,您有一个信号,无论何时创建用户,都会自动创建客户端。您的客户端模型具有强制性的ForeignKey to Category,但您的信号未设置类别。
解决方案应该是显而易见的:要么使您的类别为FK null=True
,要么得到您的信号以获取/创建相关类别。