Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

python - How can I save the same form more than once in Django 1.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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...