Python 获取django中最后插入的id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14832115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the last inserted id in django
提问by user1746291
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
我正在从其他数据库迁移一些数据,所以我使用原始 sql 查询将数据插入数据库。但我不知道如何从 Django 中的原始 sql 查询中获取最后插入的 id。我试过这个
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')"
但它给了我“(1305,'FUNCTION pydev.SCOPE_IDENTITY不存在')”的错误
So please tell me how can i get the last inserted id in raw sq l queries in django
所以请告诉我如何在 Django 的原始 sql 查询中获取最后插入的 id
回答by UnLiMiTeD
回答by adeleinr
In Django 1.6
在 Django 1.6 中
obj = Foo.objects.latest('id')
obj = Foo.objects.earliest('id')

