Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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?

1 Answer

0 votes
by (106k points)

To clone a Django model instance object and save it to the database 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 the auto-generated key then set the new key to None.

Browse Categories

...