Foo.objects.get(pk="foo") <Foo: test>
In the database, I want to add another object which is a copy of the object above.
Suppose my table has one row. I want to insert the first row object into another row with a different primary key. How can I do that?
Just change the primary key of your object and run save().
obj = Foo.objects.get(pk=<some_existing_pk>) obj.pk = None obj.save()
If you want auto-generated key, set the new key to None.
More on UPDATE/INSERT here.
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') blog.save() # blog.pk == 1 blog.pk = None blog.save() # blog.pk == 2
In this snippet, the first
save() creates the original object, and the second
save() creates the copy.
If you keep reading the documentation, there are also examples on how to handle two more complex cases: (1) copying an object which is an instance of a model subclass, and (2) also copying related objects, including objects in many-to-many relations.
Note on miah's answer: Setting the pk to
None is mentioned in miah's answer, although it's not presented front and center. So my answer mainly serves to emphasize that method as the Django-recommended way to do it.
Historical note: This wasn't explained in the Django docs until version 1.4. It has been possible since before 1.4, though.
Possible future functionality: The aforementioned docs change was made in this ticket. On the ticket's comment thread, there was also some discussion on adding a built-in
copy function for model classes, but as far as I know they decided not to tackle that problem yet. So this "manual" way of copying will probably have to do for now.