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