Django - last insert id

I cannot get the last insert id, as usual, and I'm not sure why.

In my opinion:

comment = Comments( ...)
comment.save()
comment.id #returns None

In my model:

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

Has anyone encountered this problem before? Usually, after calling the save () method, I have access to id via comment.id, but this time it does not work.

+5
source share
4 answers

Are you setting a field value idin a row comment = Comments( ...) ? If not, why do you define a field instead of just letting Django take care of the primary key with AutoField?

If you specify IntegerField as the primary key, as you do in the example, Django will not automatically assign a value to it.

+7

AutoField:

class Comments(models.Model):
    id = models.AutoField(primary_key=True)
+2

c = Comment.object.latest()

c.pk

12 #last comment saved.
+2

Do you want to specifically install a new IntegerField named id as the primary key? Since Django already does this for you for free ...

As you said, did you try to remove the id field from your comment model?

+1
source

All Articles