将模型对象从模型复制到Django [英] Copy Model Object From a Model To Another In Django

查看:104
本文介绍了将模型对象从模型复制到Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须建模。我想将模型对象从模型复制到另一个模型对象:
Model2是Model1的副本(此模型具有太多的m2m字段)
Model1:

  class Profile(models.Model):
user = models.OneToOneField(User)
car = models.ManyToManyField(Car)
job = models。 ManyToManyField(Job)


这是一个调查应用程序。我想在他/她参加调查时保存用户的个人资料(因为他可以在调查后编辑个人资料)
我已经创建了另一个模型,以便在进行调查时保存用户个人资料(我不确定其正确的方式) p>

  class SurveyProfile(models.Model):
user = models.OneToOneField(SurveyUser)#this是另一个进行调查的模型用户
car = models.ManyToManyField(Car)
job = models.ManyToManyField(Job)

如何将用户个人资料从个人资料复制到SurveyProfile。



提前感谢

解决方案

deepcopy etc将不起作用,因为类/模型不同。



如果您确定 SurveyProfile 具有个人资料中的所有字段 *,这应该工作(未测试):

  for instance_of_model_a._meta.fields :
setattr(instance_of_model_b,field.name,getattr(instance_of_model_a,field.name))
instance_of_model_b.save()

* (在这种情况下,我建议你做一个抽象的 ProfileBase class并继承为 Profile SurveyProfile 的具体类,但这并不影响我上面提到的内容)


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

解决方案

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:
    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)

这篇关于将模型对象从模型复制到Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆