12

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

user1746291
  • 323
  • 2
  • 5
  • 15

3 Answers3

29

You can get latest create obj like this:

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

more info here

UnLiMiTeD
  • 1,000
  • 1
  • 9
  • 17
4

Try this

LastInsertId = (TableName.objects.last()).id
Merrin K
  • 1,602
  • 1
  • 16
  • 27
3

In Django 1.6

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

obj = Foo.objects.earliest('id')
adeleinr
  • 665
  • 7
  • 14