You can return the id of the last data registered with Django Model Form

Asked

Viewed 769 times

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 answer

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 function save() 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
  • 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.

  • Okay, I edited the answer and added that option.

  • Oops now yes it worked, thanks Sidon. It helped a lot guy.

  • Cool, if you can, give an upvote!

  • I’m adding one more detail to when you’ve done the save().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.