How do I clone a Django model instance object and save it to the database

0 votes

In the database, I want to add another object which is a copy of the object below:

Foo.objects.get(pk="foo")
<Foo: test>

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?

Jun 26, 2020 in Python by kartik
• 37,530 points
173 views

1 answer to this question.

0 votes

Hello @kartik,

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.

Hope this works!!

Thank You!!

answered Jun 26, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer

how can i extact all the links from a website using python and save it in a csv file ?

Hi, @Shubham, Web scraping is the technique to ...READ MORE

answered Jun 16, 2020 in Python by Gitika
• 65,970 points
2,159 views
+1 vote
1 answer

How to create a file and save it to a model's FileField in Django?

Hello @kartik, Basically, a field declared as a FileField, ...READ MORE

answered Jun 30, 2020 in Python by Niroj
• 82,880 points
6,799 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
1,020 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
461 views
0 votes
1 answer

How do I clone a Django model instance object and save it to the database?

Hello @kartik, Just change the primary key of ...READ MORE

answered Jun 22, 2020 in Python by Niroj
• 82,880 points
1,797 views
0 votes
1 answer

How do I add a link from the Django admin page of one object to the admin page of a related object?

Hello @kartik, Set show_change_link to True (False by default) in your inline ...READ MORE

answered Jun 12, 2020 in Python by Niroj
• 82,880 points
4,205 views