How to get the ID of the record just saved

╄→гoц情女王★ 提交于 2019-12-18 10:58:35

问题


I'm using Django 1.3 for one of my projects and I need to get the ID of a record just saved in the database.

I have something like the code below to save a record in the database:

n = MyData.objects.create(record_title=title, record_content=content)
n.save()

The ID of the record just saved auto-increments. Is there a way to get that ID and use it somewhere else in my code?


回答1:


Use n.id after the save.

See "Auto-incrementing primary keys".




回答2:


It would be n.pk.

To quote "Model.pk":

Regardless of whether you define a primary key field yourself, or let Django supply one for you, each model will have a property called pk. It behaves like a normal attribute on the model, but is actually an alias for whichever attribute is the primary key field for the model. You can read and set this value, just as you would for any other attribute, and it will update the correct field in the model.




回答3:


The ID will be automatically updated in your model, so immediately after your n.save() line you can read n.id and it will be populated.




回答4:


Remove save() and get pk directly:

n = MyData.objects.create(record_title=title, record_content=content)
n.pk


来源:https://stackoverflow.com/questions/6253611/how-to-get-the-id-of-the-record-just-saved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!