Copy Model Object From a Model To Another In Django

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

    This is how I do it (note: this is in Python3, you might need to change things - get rid of the dictionary comprehension - if you are using python 2):

    def copy_instance_kwargs(src, exclude_pk=True, excludes=[]):
        """
        Generate a copy of a model using model_to_dict, then make sure
        that all the FK references are actually proper FK instances.  
        Basically, we return a set of kwargs that may be used to create
        a new instance of the same model - or copy from one model
        to another.
    
        The resulting dictionary may be used to create a new instance, like so:
    
        src_dict = copy_instance_kwargs(my_instance)
        ModelClass(**src_dict).save()
    
        :param src: Instance to copy
        :param exclude_pk: Exclude the PK of the model, to ensure new records are copies.
        :param excludes: A list of fields to exclude (must be a mutable iterable) from the copy. (date_modified, for example)
        """
        # Exclude the PK of the model, since we probably want to make a copy.
        if exclude_pk:
            excludes.append(src._meta.pk.attname)
        src_dict = model_to_dict(src, exclude=excludes)
        fks={k: getattr(src, k) for k in src_dict.keys() if 
             isinstance(getattr(src, k, None), models.Model) }
        src_dict.update(fks)
        return src_dict
    

提交回复
热议问题