首页 > 解决方案 > IntegrityError Null 约束违规

问题描述

我的 django 应用程序中有三个模型……一个members模型,一个application模型和一个applications review模型。

我的会员模型看起来像这样......

class Members(models.Model):
    TITLES = (
        ('chairman', 'Chairman'),
        ('secretary', 'Secretary')
    )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=10, choices=TITLES, default='secretary')

我的应用程序模型...

class Application(models.Model):
   firstname = models.CharField(max_length=20)
   middlename = models.CharField(max_length=20)
   lastname = models.CharField(max_length=20)
   dob = DateField()

应用程序审查模型...

class ApplicationsReview(models.Model):
    APPLICATION_STATUS = (
        ('pending', 'Pending Review'),
        ('approved', 'Approved'),
        ('rejected', 'Rejected')
    )
    applicant = models.OneToOneField(Application, on_delete=models.CASCADE, primary_key=True)
    chairman = models.ForeignKey(Members, related_name='chairs', on_delete=models.CASCADE)
    secretary = models.ForeignKey(Members, related_name='secretaries', on_delete=models.CASCADE)
    application_status = models.CharField(max_length=10, choices=APPLICATION_STATUS, default='pending')
    status_justification = models.TextField()
    date = models.DateTimeField(auto_now_add=True)

创建应用程序时,我也希望实例化它的审查,因此,我在应用程序审查模型下方有以下信号......

# When an application is created, create with it an application review and associate it with the application instance

@receiver(post_save, sender=Application)
def create_application_review(sender, **kwargs):
    instance = kwargs['instance']
    created = kwargs['created']
    if created:
        ApplicationReview.objects.create(applicant=instance)

但是,当我尝试在 django admin 中添加应用程序时,出现错误

null value in column "chairman_id" violates not-null constraint
DETAIL:  Failing row contains (3, pending, 2019-02-08 03:26:04.643452+00, null, null).

该错误似乎是由于信号试图实例化ApplicationsReview实例而不提供主席和秘书的值。即使将它们设置为允许空字段也不能消除错误。我在这里缺少什么吗?

标签: djangodjango-admin

解决方案


创建ApplicationsReview需要您传递以下详细信息 -chairman, secretary, status_justification但是在创建ApplicationReview信号时,您只是传递 的值applicant,因此 Django 将字段的值假定chairman, secretary, status_justification为 Null,这就是您收到此错误的原因。

如果您想让这些字段成为非强制字段,您可以null=True, Blank=True在模型中定义字段时通过。

像这样的东西:

chairman = models.ForeignKey(Members, null=True, blank=True, related_name='chairs', on_delete=models.CASCADE)

# End

您可以参考此答案以更好地了解何时使用null=Trueblank=True或两者兼而有之。 https://stackoverflow.com/a/8609425/6280433


推荐阅读