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

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

问题描述

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

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)

如何将用户配置文件从 Profile 复制到 SurveyProfile.

How can I copy user profile from Profile to SurveyProfile.

提前致谢

推荐答案

deepcopy 等将不起作用,因为类/模型不同.

deepcopy etc won't work because the classes/Models are different.

如果您确定 SurveyProfile 具有 Profile* 中存在的所有字段,这应该可以工作(未经测试):

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

*(在这种情况下,我建议您创建一个抽象的 ProfileBase 类并将其继承为 Profile 的具体类>SurveyProfile,但这不影响我上面的内容)

* (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天全站免登陆