How to create a deep clone of a DB object in Django?

I am trying to create a full copy of the survey instance, which has several sections, and each section has several questions, and finally, each question has several options. I am using standard django 1.3.1 with MySQL. I need to create a full copy of all these elements for another survey owner. I currently have an opinion:

survey_new = survey survey_new.title = survey.title + ' -- Copy' survey_new.owner = str(new_owner_id) survey_new.created = datetime.now() survey_new.pk = None survey_new.save() for sec in survey.sections.all().order_by('order'): sec_n = sec sec_n.survey_id = survey_new.id sec_n.pk = None sec_n.save() for q in sec.questions.all().order_by('order'): q_n = q q_n.section_id = sec_n.id q_n.pk = None q_n.save() for op in q.options.all().order_by('order'): op_n = op op_n.question_id = q_n.id op_n.pk = None op_n.save() 

However, this seems to go through all the cycles without any errors and just creates a copy of the survey. I was hoping this would copy the survey, sections, questions, options for this survey. I just can’t understand what I'm doing wrong here.

+6
source share
2 answers

Googling "django deep copy" returns this on the first page: http://www.nerdydork.com/copy-model-object-in-django.html

The given code example:

 from copy import deepcopy old_obj = deepcopy(obj) old_obj.id = None old_obj.save() 

If I understand your question correctly, you will need to change a few more fields before saving.

+9
source

I think this happens because the survey assigned by survey_new in this line of code

 survey_new = survey 

Then when survey_new saved

 survey_new.title = survey.title + ' -- Copy' survey_new.owner = str(new_owner_id) survey_new.created = datetime.now() survey_new.pk = None survey_new.save() 

survey became equal to survey_new . For example, you can check it like this

 id(survey) # 50016784 id(survey_new) # 50016784 

or the equivalent of Django

 survey.id # 10 survey_new.id # 10 

To find out the problem, all the necessary objects must be collected before the appointment

 survey_section = survey.sections.all().order_by('order') # ... all other questions and options survey_new = survey survey_new.title = survey.title + ' -- Copy' survey_new.owner = str(new_owner_id) # ... your remaining code 
+1
source

Source: https://habr.com/ru/post/906347/


All Articles