简体   繁体   中英

Using Python's deepcopy for different django models

I have two different django models with many attributes which differ in only 1 or 2 attributes. Based on some conditions, I would want to read one row from one model of a table and write to the other table. As of now, I am reading a row into an object, doing a deepcopy and then changing the class name using python's __class__ so that data of other attributes is persisted and I can add details of other attributes. The reason for doing this is because there are so many attributes and manually trying to copy every attribute should be avoided if we can.

An example code goes something like this. There is a Program model and a ProgramRepository model. The ProgramRepository model has an extra attribute owner

    program = get_object_or_404(Program,pk=id)
    new_program = copy.deepcopy(program)
    new_program.id = None
    new_program.__class__ = ProgramRepository
    new_program.owner = creator
    new_program.save()

Will this cause any problems? Is there a better way to do this?

You can use multiple inheritance in Django models which is a better way

class FieldProgrammer(models.Model):

    field1 = models.IntegerField()
    field2 = models.CharField() #etc
    class Meta:
        abstract=True #abstract class does not create a db table

class Programmer(FieldProgrammer):

    pass

class ProgramRepository(FieldProgrammer):

    owner = models.CharFiled()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM