Get the last inserted id in django
Asked Answered
D

3

13

I am migrating some data from other databases , so i am using raw sql queries for inserting data into database . But i don't know how to get last inserted id from raw sql queries in django. I have tried this

affected_count1=cursor2.execute("table')")

and

SELECT IDENT_CURRENT(‘MyTable’)

but it gives me the error of "(1305, 'FUNCTION pydev.SCOPE_IDENTITY does not exist')"

So please tell me how can i get the last inserted id in raw sq l queries in django

Directive answered 12/2, 2013 at 12:1 Comment(2)
#2548993Diannadianne
which db engine are you using?Willhite
R
33

You can get latest create obj like this:

obj = Foo.objects.latest('id')

more info here

Rogation answered 12/2, 2013 at 12:38 Comment(3)
No, this is unrelated to the question.Lifeline
I know it is unrelated to the question: but whenever I try to add default=Foo.objects.latest('id') to a ForeignKey in a model; I get the error "App registry isn't ready yet." while launching. (Django 1.7a2); do you know why?Fascia
is latest, use concurrency ?Imbecility
M
4

Try this

LastInsertId = (TableName.objects.last()).id
Margherita answered 20/1, 2022 at 12:28 Comment(2)
What's the benefit of using last().id over using .latest('id'), as proposed in the top-voted answer?Tadd
.latest('id') Throwed an error :> TypeError: Object of type TableName is not JSON serializableMargherita
E
3

In Django 1.6

obj = Foo.objects.latest('id')

obj = Foo.objects.earliest('id')
Eidetic answered 14/12, 2013 at 21:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.