Django: Two different child classes point to same parent class

前端 未结 4 1155
名媛妹妹
名媛妹妹 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:37

    You can't really do that with subclassing. When you subclass Person, you're implicitly telling Django that you'll be creating subclasses, not Person objects. It's a PITA to take a Person and transmogrify it into a OtherPerson later.

    You probably want a OneToOneField instead. Both Client and OtherPerson should be subclasses of models.Model:

    class Client(models.Model):
        person = models.OneToOneField(Person, related_name="client")
        # ...
    
    class OtherPerson(models.Model):
        person = models.OneToOneField(Person, related_name="other_person")
        # ...
    

    Then you can do things like:

    pers = Person(...)
    pers.save()
    client = Client(person=pers, ...)
    client.save()
    other = OtherPerson(person=pers, ...)
    other.save()
    
    pers.other.termination_date = datetime.now()
    pers.other.save()
    

    See https://docs.djangoproject.com/en/dev/topics/db/examples/one_to_one/ for more.

提交回复
热议问题