Copy Model Object From a Model To Another In Django
django, django-models
Solution
`deepcopy` etc won't work because the classes/Models are different.
If you're certain that `SurveyProfile` has the all of the fields present in `Profile`*, this should work (not tested it):
for field in instance_of_model_a._meta.fields:
if field.primary_key == True:
continue # don't want to clone the PK
setattr(instance_of_model_b, field.name, getattr(instance_of_model_a, field.name))
instance_of_model_b.save()
`*` (in which case, I suggest you make an abstract `ProfileBase` class and inherit that as a concrete class for `Profile` and `SurveyProfile`, but that doesn't affect what I've put above)
Problem
I have to model. I want to copy model object from a model to another: Model2 is copy of Model1 (this models has too many m2m fields) Model1: ``` class Profile(models.Model): user = models.OneToOneField(User) car = models.ManyToManyField(Car) job = models.ManyToManyField(Job) . . ``` This is a survey application. I want to save user's profile when he/she attends the survey (because he can edit profile after survey) I have created another model to save user profile when he takes survey (Im not sure its the right way) ``` class SurveyProfile(models.Model): user = models.OneToOneField(SurveyUser) #this is another model that takes survey users car = models.ManyToManyField(Car) job = models.ManyToManyField(Job) ``` How can I copy user profile from Profile to SurveyProfile. Thanks in advance