Django: Two different child classes point to same parent class

前端 未结 4 1140
名媛妹妹
名媛妹妹 2021-02-16 00:15

I have a model Person which stores all data about people. I also have a Client model which extends Person. I have another extending model OtherPe

4条回答
  •  失恋的感觉
    2021-02-16 00:46

    Okay, I hate to answer my own question, especially since it is sort of a repeat of (Django model inheritance: create sub-instance of existing instance (downcast)?

    @Daniel Roseman got me out of a jam AGAIN. Gotta love that guy!

    person = Person.objects.get(id=)
    client = Client(person_ptr_id=person.id)
    client.__dict__.update(person.__dict__)
    client.save()
    other_person = OtherPerson(person_ptr_id=person.id)
    other_person.__dict__.update(person.__dict__)
    other_person.save()
    

    If I have an existing Client and want to make an OtherPerson from them, which is my exact use-case, I just do this:

    client_id = 
    p = Person.objects.get(id=client_id)
    o = OtherPerson(person_ptr_id=p.id) # Note Person.id and Client.id are the same.
    o.__dict__.update(p.__dict__)
    o.save()
    

    Now the person shows up as a Client on the clients screen and as an OtherPerson on the other person screen. I can get the OtherPerson version of the Person which has all the OtherPerson details and functions or I can get a Client version of that Person which has all the Client details and functions.

提交回复
热议问题