tags:

views:

429

answers:

4

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.

+1  A: 

Do you want to specifically set a new IntegerField called id as the primary key? Because Django already does that for you for free...

That being said, have you tried removing the id field from your comment model?

AlbertoPL
+3  A: 

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.

Steve Losh
no, I don't define id it's auto incremented. I didn't realize that, thanks.
Joe
+1  A: 

To define an automatically set primary key use AutoField:

class Comments(models.Model):
    id = models.AutoField(primary_key=True)
Alexander Ljungberg
A: 

I was looking for this :) thanks

Asinox