27👍
✅
Googling "django deep copy" returns this on the first page: Copy Model Object in Django | Nerdy Dork
The code sample given is:
from copy import deepcopy
old_obj = deepcopy(obj)
old_obj.id = None
old_obj.save()
If I understand your question correctly, you will want to change some more fields before saving.
1👍
I think this happens because survey
assigned to survey_new
on this line of code
survey_new = survey
An 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 so
id(survey)
# 50016784
id(survey_new)
# 50016784
or Django equivalent
survey.id
# 10
survey_new.id
# 10
To figure out the issue all required objects have to be collected before assignment
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
- [Django]-Django: list all reverse relations of a model
- [Django]-Default filter in Django model
- [Django]-How to get username from Django Rest Framework JWT token
Source:stackexchange.com