How to modify a queryset and save it as new objects?

强颜欢笑 提交于 2019-12-05 02:48:32

问题


I need to query for a set of objects for a particular Model, change a single attribute/column ("account"), and then save the entire queryset's objects as new objects/rows. In other words, I want to duplicate the objects, with a single attribute ("account") changed on the duplicates. I'm basically creating a new account and then going through each model and copying a previous account's objects to the new account, so I'll be doing this repeatedly, with different models, probably using django shell. How should I approach this? Can it be done at the queryset level or do I need to loop through all the objects?

i.e.,

MyModel.objects.filter(account="acct_1")
# Now I need to set account = "acct_2" for the entire queryset, 
# and save as new rows in the database

回答1:


From the docs:

If the object’s primary key attribute is not set, or if it’s set but a record doesn’t exist, Django executes an INSERT.

So if you set the id or pk to None it should work, but I've seen conflicting responses to this solution on SO: Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object

This solution should work (thanks @JoshSmeaton for the fix):

models = MyModel.objects.filter(account="acct_1")
for model in models:
  model.id = None
  model.account = "acct_2"
  model.save()

I think in my case, I have a OneToOneField on the model that I'm testing on, so it makes sense that my test wouldn't work with this basic solution. But, I believe it should work, so long as you take care of OneToOneField's.



来源:https://stackoverflow.com/questions/16149871/how-to-modify-a-queryset-and-save-it-as-new-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!