Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - last insert id

Tags:

python

django

I can't get the last insert id like I usually do and I'm not sure why.

In my view:

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

In my Model:

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

Has anyone run into this problem before? Usually after I call the save() method, I have access to the id via comment.id, but this time it's not working.

like image 270
Joe Avatar asked Jul 21 '09 19:07

Joe


1 Answers

Are you setting the value of the id field in the comment = Comments( ...) line? If not, why are you defining the field instead of just letting Django take care of the primary key with an AutoField?

If you specify in IntegerField as a primary key as you're doing in the example Django won't automatically assign it a value.

like image 110
Steve Losh Avatar answered Oct 20 '22 01:10

Steve Losh