How to get the ID of a just created record in Django?
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.
Remove save() and get pk directly:
n = MyData.objects.create(record_title=title, record_content=content)
n.pk
Use n.id
after the save.
See "Auto-incrementing primary keys".
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.