如何修改queryset并将其保存为新对象

如何修改queryset并将其保存为新对象

本文介绍了如何修改queryset并将其保存为新对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要查询特定模型的一组对象,更改单个属性/列(account),然后将整个查询对象作为新对象/行保存。换句话说,我想复制对象,在重复项上改变一个属性(account)。我基本上是创建一个新帐户,然后通过每个模型,并将以前的帐户的对象复制到新帐户,所以我会反复使用不同的模型,可能使用django shell。我该怎么办?可以在查询级别完成,还是需要遍历所有对象?

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?

ie

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


推荐答案

从:

所以如果你将 id pk 设置为None,它应该可以工作,但是对此解决方案的冲突反应如下:

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

此解决方案应该工作(感谢@JoshSmeaton的修复):

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

我想在我的情况下,我有一个 OneToOneField 在我正在测试的模型上,所以我的测试不适用于这个基本的解决方案是有道理的。但是,我相信它应该有效,只要你照顾OneToOneField的。

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.

这篇关于如何修改queryset并将其保存为新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 21:50