IntegrityError空约束违反

时间:2019-02-08 04:10:55

标签: django django-admin

我的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实例而未提供董事长和秘书的值所致。即使将其设置为允许空字段也不会消除该错误。我在这里想念什么吗?

1 个答案:

答案 0 :(得分:1)

创建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