Copy Model Object From a Model To Another In Django

后端 未结 5 767
挽巷
挽巷 2021-01-03 00:41

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


        
5条回答
  •  囚心锁ツ
    2021-01-03 01:22

    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.

提交回复
热议问题