Django:两个不同的子类指向同一个父类

2024-06-28

我有一个模型Person它存储有关人的所有数据。我也有一个Client扩展 Person 的模型。我有另一个扩展模型OtherPerson这也扩展了Person模型。我想创建一个指向Person,并且还创建一个OtherPerson记录指向那个的Person。基本上我想要一个Person对象被视为Client和一个OtherPerson,取决于当前视图。这可以通过 Django 的 ORM 实现吗?或者我是否需要以某种方式编写原始查询来创建此场景。我非常确定从数据库方面来说这是可能的,因为两个子类都只会使用其 person_ptr_id 字段指向父 Person 类。

简而言之,如果我创建一个Client(因此Person),我还可以创建一个OtherPerson使用底座的对象Person来自Client。这样我就可以将它们视为Client或作为OtherPerson,保存一个会影响Person各自的领域?

“水平”多态性?

这是我的模型的简化版本,以防澄清:

class Person(models.Model):
    """
        Any person in the system will have a standard set of details, fingerprint hit details, some clearances and items due, like TB Test.
    """
    first_name = models.CharField(db_index=True, max_length=64, null=True, blank=True, help_text="First Name.")
    middle_name = models.CharField(db_index=True, max_length=32, null=True, blank=True, help_text="Middle Name.")
    last_name = models.CharField(db_index=True, max_length=64, null=True, blank=True, help_text="Last Name.")
    alias = models.CharField(db_index=True, max_length=128, null=True, blank=True, help_text="Aliases.")
    .
    .
    <some person methods like getPrintName, getAge, etc.>

class Client(Person):
    date_of_first_contact = models.DateField(null=True, blank=True)
    .
    .
    <some client methods>


class OtherPerson(Person):
    active_date = models.DateField(null=True, blank=True)
    termination_date = models.DateField(null=True, blank=True)
    .
    .
    <some other person methods>

好吧,我讨厌回答我自己的问题,特别是因为它有点重复(Django 模型继承:创建现有实例的子实例(向下转型)? https://stackoverflow.com/questions/4064808/django-model-inheritance-create-sub-instance-of-existing-instance-downcast

@Daniel Roseman 再次让我摆脱困境。一定要爱那个人!

person = Person.objects.get(id=<my_person_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()

如果我有一个现有的Client并想做一个OtherPerson从他们那里,这就是我的确切用例,我只是这样做:

client_id = <ID of Client/Person I want to create an OtherPerson with>
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()

现在,此人在客户屏幕上显示为客户,并在其他人屏幕上显示为其他人。我可以获得该人的其他人版本,其中包含所有其他人的详细信息和功能,或者我可以获得该人的客户端版本,其中包含所有客户端详细信息和功能。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Django:两个不同的子类指向同一个父类 的相关文章

随机推荐