0
Guys, I have a question.
I’m using Django and I wonder if you have how to return the id of the data registered with Modelform, example when you give a model.save() can recover the id of this guy who has just been registered?
0
Guys, I have a question.
I’m using Django and I wonder if you have how to return the id of the data registered with Modelform, example when you give a model.save() can recover the id of this guy who has just been registered?
1
You can take the id
from the register you just registered, let’s say you have a model named after Item
, with the fields descricao
and quantidade atual
, so you register an item and can already pick, at the time of registration, the id
(the example below was created in the Django shell):
from .models import Item
ultimo_id = Item.objects.create(descricao='teste1', quantidade_atual=10).id
print(ultimo_id)
Exit:
7
But if you want the id
last registration but is not at the time of registration (actually this option will always work), you can do:
ultimo_id = Item.objects.latest('pk').pk
print(ultimo_id)
Exit:
7
Edited
As indicated in the comments, the record is being saved in the bank through the functionsave()
of a form, in which case just do:
registro = meu_form.save()
In this way Voce will have access to all fields of the notation ataves record registro.fieldname
, to print the pk
which, in fact, is the id
, do:
print(registro.id)
Exit:
7
New edition
If by chance, for which reason you already save without assigning the return to a variable (as in your example:meu_form.save()
) and need to pick up the fields of saved record, do:
registro = meu_form.instance
Browser other questions tagged python-3.x django
You are not signed in. Login or sign up in order to post.
Then only that in the case I am creating a new record with Modelform from Django; ex:
meu_form.save()
and here recover the id that was created in the bank.– Robson Silva
Okay, I edited the answer and added that option.
– Sidon
Oops now yes it worked, thanks Sidon. It helped a lot guy.
– Robson Silva
Cool, if you can, give an upvote!
– Sidon
I’m adding one more detail to when you’ve done the
save()
.– Sidon