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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:35:29  来源:igfitidea点击:

Get the last inserted id in django

pythondjangorawsql

提问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

You can get latest create obj like this:

您可以像这样获得最新的 create obj:

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

more info here

更多信息在这里

回答by adeleinr

In Django 1.6

在 Django 1.6 中

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

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