2

I have seen the following link: How do I clone a Django model instance object and save it to the database?

But this one does only 1 object cloning. What if I want to clone multiple objects cloned. For eg. something like this:

foo_objects = Foo.objects.filter(col1=value1)
foo_objects.pk = None
foo_objects.col2=value2
foo_objects.save()

I know I can use bulk insert. Please suggest another method if any.

Community
  • 1
  • 1
Anuj
  • 1,130
  • 2
  • 18
  • 35

2 Answers2

3

There is no update method on queryset that can update relationship fields. You would have to either use bulk_create() to create/save multiple objects. But before that iterate through queryset to set attributes appropriately.

Something like

foo_objects = Foo.objects.filter(col1=value1)
for f in foo_objects:
    f.pk = None
    f.col2=value2
    f.save() #either do this or save with bulk create as

Foo.objects.bulk_create(foo_objects)
Rohan
  • 50,238
  • 11
  • 84
  • 85
  • This is what I also came up to. I didn't want to create full objects. I have used bulk_create finally. – Anuj Feb 22 '14 at 07:59
0

if you don't want to use bulk create, you can control transaction commit by your own like this

from django.db import transaction

with transaction.commit_on_success():
        for foo_object in foo_objects:
            foo_object.pk = None
            foo_objects.col2=value2
            foo_objects.save()
jargalan
  • 4,696
  • 5
  • 25
  • 36