Clone an inherited django model instance

前端 未结 1 1330
深忆病人
深忆病人 2021-02-09 02:04

When I clone a django model instance I used to clean the \'pk\' field. This seems not to work with an inherited model :

Take this :

class ModelA(models.M         


        
1条回答
  •  长发绾君心
    2021-02-09 02:49

    c=ModelC(info1="aaa",info2="bbb",info3="ccc")
    # creates an instance
    
    c.save()
    # writes instance to db
    
    c.pk=None
    # I doubt u can nullify the auto-generated pk of an existing object, because a pk is not nullable
    c.save()
    # if I'm right nothing will happen here.
    

    So c will always be the same object. If you want to clone it you need to generate a new object. Either with a constructor within ModelC:

    def __init__(another_modelC_obj=null, self):
       if another_modelC_obj:
          # for every field in another_modelC_obj: do self.field = another_modelC_obj.field
       super().__init__()
    

    so you can go

    c2=ModelC(c)
    

    Or call it directly with:

    c2=ModelC(c.info1, c.info2, c.info3)
    

    Then c2 and c will be identical despite of their pk

    0 讨论(0)
提交回复
热议问题