last insert id

1,118 views
Skip to first unread message

Mathieu Blondel

unread,
Apr 18, 2006, 9:15:50 PM4/18/06
to Django developers
Hi,

I'm a new comer to Django so please forgive me if the following has
already a solution.

When one saves an object with the save() method, a common need is to
get the id corresponding to the row that has just been inserted.

p = polls.Poll(...)
p.save()
p.id # is set to None

So here are two possible solutions,
1) Either update the primary key columns from a row when save() is
called
2) Or implement a reload() method which would update the whole object
variables

Thanks for the great work achieved with Django,
Mathieu

apr...@gmail.com

unread,
Apr 19, 2006, 10:24:33 AM4/19/06
to Django developers
Strange, for me it works like said in 1). After the new object is
saved, the id field is not None, but the true id of the object in
database. Maybe I did not understand something?

Also, if you look at the tutorial at
http://www.djangoproject.com/documentation/tutorial1/ it says:

# No polls are in the system yet.
>>> polls.get_list()
[]

# Create a new Poll.
>>> from datetime import datetime
>>> p = polls.Poll(question="What's up?", pub_date=datetime.now())

# Save the object into the database. You have to call save()
explicitly.
>>> p.save()

# Now it has an ID. Note that this might say "1L" instead of "1",
depending
# on which database you're using. That's no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
>>> p.id
1

Adrian Holovaty

unread,
Apr 20, 2006, 5:46:10 PM4/20/06
to django-d...@googlegroups.com
On 4/18/06, Mathieu Blondel <mblo...@gmail.com> wrote:
> When one saves an object with the save() method, a common need is to
> get the id corresponding to the row that has just been inserted.
>
> p = polls.Poll(...)
> p.save()
> p.id # is set to None
>
> So here are two possible solutions,
> 1) Either update the primary key columns from a row when save() is
> called
> 2) Or implement a reload() method which would update the whole object
> variables

Hi Mathieu,

Django currently does exactly what you described in "1" -- when you
call save() for the first time, the primary key attribute of the
object is updated with the ID of the newly-saved record. This assumes
that field is defined as an AutoField in the model.

Adrian

--
Adrian Holovaty
holovaty.com | djangoproject.com

Reply all
Reply to author
Forward
0 new messages