Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django-最后一个插入id_Python_Django - Fatal编程技术网

Python Django-最后一个插入id

Python Django-最后一个插入id,python,django,Python,Django,我无法像往常一样获得最后一个插入id,我不知道为什么 我认为: comment = Comments( ...) comment.save() comment.id #returns None 在我的模型中: class Comments(models.Model): id = models.IntegerField(primary_key=True) 以前有人遇到过这个问题吗?通常在调用save()方法后,我可以通过comment.id访问id,但这次它不起作用。是否要专门将名为i

我无法像往常一样获得最后一个插入id,我不知道为什么

我认为:

comment = Comments( ...)
comment.save()
comment.id #returns None
在我的模型中:

class Comments(models.Model):
    id = models.IntegerField(primary_key=True)

以前有人遇到过这个问题吗?通常在调用save()方法后,我可以通过comment.id访问id,但这次它不起作用。

是否要专门将名为id的新整型字段设置为主键?因为Django已经免费为你做了


话虽如此,您是否尝试过从注释模型中删除id字段?

您是否在
comment=Comments(…)中设置
id
字段的值
line?如果没有,为什么要定义字段,而不是让Django使用AutoField处理主键


如果像在示例中那样在IntegerField中指定主键,Django不会自动为其赋值。

要定义自动设置的主键,请使用AutoField:

class Comments(models.Model):
    id = models.AutoField(primary_key=True)
干脆

c = Comment.object.latest()
这将返回最后插入的注释

c.pk

12 #last comment saved.

你设置过身份证吗?您没有使用自动字段。不,我没有定义id,它是自动递增的。我没有意识到,谢谢。那应该是
对象
,而不是
对象