Coder Perfect

How do I save a Django model instance object to the database after cloning it?


<Foo: test>

I’d like to add another object to the database that is a clone of the one above.

Assume my table contains only one row. I’d like to copy the first row object and paste it into a second row with a different primary key. How can I do that?

Asked by user426795

Solution #1

Simply modify your object’s main key and save ().

obj = Foo.objects.get(pk=<some_existing_pk>) = None

Set the new key to None if you want an auto-generated key.

Here’s more about UPDATE/INSERT. Official documentation on copying model instances:

Answered by miah

Solution #2

The Django documentation for database queries includes a section on copying model instances. Assuming your primary keys are autogenerated, you get the object you want to copy, set the primary key to None, and save the object again:

blog = Blog(name='My blog', tagline='Blogging is easy') # == 1 = None # == 2

The first save() generates the original object, and the second save() creates the copy in this excerpt.

If you continue reading the documentation, you’ll get examples of how to deal with two more complex scenarios: (1) duplicating an object that is an instance of a model subclass, as well as (2) duplicating related objects, such as objects in many-to-many relationships.

It mostly serves to highlight that procedure as the Django-recommended approach.

This wasn’t explained in the Django documentation until version 1.4. However, it has been possible since before 1.4.

Future functionality: In this ticket, the aforementioned docs change was made. There was also some discussion on the ticket’s comment thread about introducing a built-in copy method for model classes, but as far as I know, they decided not to handle that topic yet. So for the time being, this “manual” method of copying will have to suffice.

Answered by S. Kirby

Solution #3

Take caution in this area. If you’re in a loop of some kind and obtaining things one by one, this can be very expensive. If you don’t want the database call, simply type:

from copy import deepcopy

new_instance = deepcopy(object_you_want_copied) = None

It accomplishes the same goal as some of the previous responses, except it does not use the database to fetch an object. This is also beneficial if you need to duplicate an item that doesn’t yet exist in the database.

Answered by Troy Grosfield

Solution #4

Use the code below:

from django.forms import model_to_dict

instance = Some.objects.get(slug='something')

kwargs = model_to_dict(instance, exclude=['id'])
new_instance = Some.objects.create(**kwargs)

Answered by t_io

Solution #5

Here’s a clone snippet you can use in your model to accomplish this:

def clone(self):
  new_kwargs = dict([(, getattr(old, for fld in old._meta.fields if !=]);
  return self.__class__.objects.create(**new_kwargs)

Answered by Dominic Rodger

Post is based on