完整性错误Django外键设置为无

yxyvkwin  于 2023-01-31  发布在  Go
关注(0)|答案(1)|浏览(149)

我在为作者变量设置一个模型字段的外键时遇到了一个问题。

class BugTracker(models.Model):
    project_number= models.IntegerField(primary_key=True)
    assignee=  models.ForeignKey(Developer, on_delete=models.CASCADE)
    priority = models.CharField(max_length=10, choices=priority_choices)
    summary=models.TextField()
    status= models.CharField(max_length=20, choices=progress)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    created_at=models.DateTimeField(default=timezone.now)
    updated_at=models.DateTimeField(auto_now=True)
   
    def __str__(self):
        return self.summary

    def get_absolute_url(self): 
        return reverse("bug_list")

"IntegrityError at /projects/create/
NOT NULL constraint failed: core_bugtracker.author_id
Request Method: POST
Request URL:    http://127.0.0.1:8000/projects/create/
Django Version: 4.1.5
Exception Type: IntegrityError
Exception Value:    
NOT NULL constraint failed: core_bugtracker.author_id"

只要我将“null=True”添加到ForeignKey字段中,它就可以工作,而且我没有收到错误,但模板显示我的变量({bug.author}}等于“None”,无论我以谁的身份登录。我多次尝试删除我的数据库和迁移文件,但它仍然不起作用。

ovfsdjhp

ovfsdjhp1#

如果您在保存BugTracker模型时没有将“author”作为字段传递,则会得到({bug.author}}作为None,因为您在“author”字段声明中设置了“null=True”-这意味着您可以在不传递“author”字段的情况下保存BugTracker模型,并且默认为null/None。
如果您想在bug_tracker_object中设置/添加一个author对象,您可以执行以下操作。bug_tracker_object是您使用project_number、assignee、priority等字段填充的BugTracker对象。)

author_object = Author.objects.get(id=<your_author_id>)
bug_tracker_object.author_object = author_object 
bug_tracker_object.save()

相关问题