Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy Model Object From a Model To Another In Django

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

like image 885
TheNone Avatar asked May 30 '12 13:05

TheNone


2 Answers

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)

like image 190
Steve Jalim Avatar answered Sep 19 '22 23:09

Steve Jalim


I'm having a tough time understanding what you wrote above, consequently I'm not 100% certain if this will work, but what I think I would do is something like this, if I'm understanding you right:

class Model2Form(ModelForm):
    class Meta:
        model = models.Model2

and then

f = Model2Form(**m1.__dict__)
if f.is_valid():
    f.save()

But I think this looks more like poor database design then anything, without seeing the entire model1 I can't be certain. But, in any event, I'm not sure why you want to do that anyway, when you can simply use inheritance at the model level, or something else to get the same behavior.

like image 28
James R Avatar answered Sep 17 '22 23:09

James R