django.db.utils.IntegrityError: NOT NULL constraint failed: blog_blog.author_id的错误解决方法

这几天在学django,项目是做自己的博客,然后在shell命令创建新博客的时候出现了以下的错误

django.db.utils.IntegrityError: NOT NULL constraint failed: blog_blog.author_id

由错误提示可以知道是数据库的非空约束出了问题,并且是在blog.auther_id这里有问题

然后重复看我的创建流程,首先先回去看我的models模型,源码如下

from django.db import models
from django.contrib.auth.models import User

#  创建博客分类模型
class BlogType(models.Model):
    type_name = models.CharField(max_length=15)
    def __str__(self):
        return self.type_name

#  创建博客模型
class Blog(models.Model):
    title = models.CharField(max_length=50)
    blog_type = models.ForeignKey(BlogType, on_delete=models.DO_NOTHING)
    content = models.TextField()
    author = models.ForeignKey(User, on_delete=models.DO_NOTHING)
    created_time = models.DateTimeField(null=True, auto_now_add=True)
    last_updated_time = models.DateTimeField(null=True, auto_now=True)
    def __str__(self):
        return "<Blog: %s>" % self.title 

可以知道我在作者这里使用的外键,并且作者这个类我没有在model中定义,所以我的shell代码如下

>>> from django.contrib.auth.models import User
>>> User.objects.all()
<QuerySet [<User: xxz>]>
>>> blog.auther = User.objects.all()[0]
>>> blog.save()

sqlite3.IntegrityError: NOT NULL constraint failed: blog_blog.author_id

然后就出现了问题,解决方法其实也很简单,就是再输入

>>> blog.author_id = 1
>>> blog.save()

问题就解决了,那么现在讨论问题怎么出现的

https://docs.djangoproject.com/en/1.11/ref/models/instances/

扫描二维码关注公众号,回复: 4536379 查看本文章

在这边django文档中有这么一句话

Model.pk

Regardless of whether you define a primary key field yourself, or let Django supply one for you, each model will have a property called pk. It behaves like a normal attribute on the model, but is actually an alias for whichever attribute is the primary key field for the model. You can read and set this value, just as you would for any other attribute, and it will update the correct field in the model.

翻译过来就是(我英语不好用的谷歌翻译哈)

无论您是自己定义主键字段,还是让Django为您提供一个,每个模型都有一个名为pk的属性。 它的行为类似于模型上的普通属性,但实际上是属于模型主键字段的别名的别名。 您可以像读取任何其他属性一样读取和设置此值,它将更新模型中的正确字段。

大概意思就是你在models中定义的所有的类(看作数据库中的一张表),都会有一个主键id,你每创建一个对象,就像前面写的blog=Blog()一样,blog中就会自动分配一个id,并且递增,同理,在blog中的auther一样,要定义一个id,但之前没有定义,所以这里手动定义。

猜你喜欢

转载自blog.csdn.net/qq_38115310/article/details/83818617