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 22, 2020 in Python by kartik
• 37,530 points
1,404 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 is helpfull!!

Thank You!!

answered Jun 22, 2020 by Niroj
• 82,780 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,930 points
1,912 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,780 points
5,593 views
0 votes
3 answers

Python Selenium best tutorials for beginners

Hope this will help you...Python Tutorial READ MORE

answered Feb 11, 2019 in Python by aldrinjohn
• 140 points
2,459 views
0 votes
1 answer
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,780 points
3,414 views