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,520 points
1,095 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,840 points

Related Questions In Python

0 votes
0 answers
0 votes
1 answer
–1 vote
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,770 points
4,106 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,840 points
2,460 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,840 points
1,569 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,840 points
10,612 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,840 points
14,842 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP