8

I have a model Product and a corresponding form Product and I need to update the stock with lets say 5 product, so I input the data for the Product and ask how many items of this product I want to store, because all products to save are the same, except for Django default ID, i was thinking of doing something like this in the view:

for i in range(0, 5):
   form.save()

Unfortunately this only saves the last form.

How else can I achieve what I need?

Crixx93
  • 727
  • 10
  • 22
  • 1
    Save one, then [create clones of the one from the form](http://stackoverflow.com/questions/4733609/how-do-i-clone-a-django-model-instance-object-and-save-it-to-the-database) – Colonel Thirty Two Oct 08 '15 at 22:37

1 Answers1

8

Calling save with commit=False returns an instance that is not saved to the database.

instance = form.save(commit=False)

You can the save the instance multiple times in a loop. By setting the primary key to None, a new object will be saved each time.

for i in range(0, 5):
    instance.pk = None
    instance.save()
Alasdair
  • 298,606
  • 55
  • 578
  • 516