Copy Model Object From a Model To Another In Django

后端 未结 5 847
挽巷
挽巷 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:39

    Here's the function I've been using, it builds on model_to_dict. Model_to_dict just returns the ids of foreign keys + not their instances, so for those I replace them with the model itself.

    def update_model(src, dest):
        """
        Update one model with the content of another.
    
        When it comes to Foreign Keys, they need to be
        encoded using models and not the IDs as
        returned from model_to_dict.
    
        :param src: Source model instance.
        :param dest: Destination model instance.
        """
        src_dict = model_to_dict(src, exclude="id")
        for k, v in src_dict.iteritems():
            if isinstance(v, long):
                m = getattr(src, k, None)
                if isinstance(m, models.Model):
                    setattr(dest, k, m)
                    continue
    
            setattr(dest, k, v)
    

提交回复
热议问题