django - 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
实例而不提供主席和秘书的值。即使将它们设置为允许空字段也不能消除错误。我在这里缺少什么吗?
解决方案
创建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=True
,blank=True
或两者兼而有之。
https://stackoverflow.com/a/8609425/6280433
推荐阅读
- c# - C# WPF MVVM DataGrid MouseBinding for rows only
- c# - 如何设置本地离线局域网多人游戏?
- python-3.x - TKinter Splashscreen 不适用于 Python 3.6 基于 GUI 的应用程序
- json - Scala Json 使用 null 或 Option[Int] 反序列化
- reactjs - 使用 React 的内联 SVG(没有 JSX)
- vb.net - 如何将字符串添加到列表(索引)取决于 vb.net 中字符串的条件
- ios - 调用字符串扩展,包括从 Objective-C 用 Swift 编写的函数
- sql - 计算不同的出现
- c++ - 位向量和位串有什么区别?
- c# - Sorted Dictionary 和 List<>() 在 VS 2010 中有错误