6

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
4
  • I think I'm confused. Do you want to duplicate the objects, and set a new account to them?
    – bozdoz
    Apr 22, 2013 at 14:47
  • yes. Sorry, I'll try to reword it to make it clearer.
    – B Robster
    Apr 22, 2013 at 14:48
  • You can bulk update, and you can bulk insert, but you can't bulk update and create new in a single line. You have to loop through the queryset. Apr 22, 2013 at 14:54
  • Thanks, @JoshSmeaton . Looks like bozdoz's answer is the way to go then.
    – B Robster
    Apr 22, 2013 at 18:16

1 Answer 1

9

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.

5
  • but that would save over the old objects, would it not?
    – B Robster
    Apr 22, 2013 at 14:47
  • Yes. I was confused by the question. Apologies @BenRoberts
    – bozdoz
    Apr 22, 2013 at 14:47
  • This will override the field.
    – Ahsan
    Apr 22, 2013 at 14:48
  • You just need to set the id to None, I've updated your answer. Apr 22, 2013 at 14:52
  • Doesn't work in my version of django, but I see from other questions that it should work in others: stackoverflow.com/questions/4733609/…
    – bozdoz
    Apr 22, 2013 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.