我有一个模型Person
,可以存储有关人的所有数据。我也有一个Client
扩展Person的模型。我还有另一个扩展模型OtherPerson
,它也扩展了Person
模型。我想创建一个指向a的客户Person
,并且还创建一条指向该客户的OtherPerson
记录Person
。基本上,我希望将一个Person
对象视作aClient
和and an OtherPerson
,具体取决于当前视图。Django的ORM是否可以做到这一点,或者我是否需要以某种方式编写Raw查询来创建这种情况。我从数据库方面肯定是有可能的,因为两个子类都将使用其person_ptr_id字段指向父Person类。
简而言之,如果我创建了一个Client
(并因此创建了Person
),我是否也可以OtherPerson
使用中的基数Person
来创建对象Client
。这样,我可以将它们视为Client
OR或OR OtherPerson
,保存一个将影响Person
每个OR的字段?
“水平”多态性?
这是我的模型的简化版本,以防万一:
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模型继承:创建现有实例的子实例(向下转换?)的重复?
@丹尼尔·罗斯曼(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()
现在,此人在客户屏幕上显示为“客户”,在其他人屏幕上显示为“其他人”。我可以获得具有所有OtherPerson详细信息和功能的Person的OtherPerson版本,或者可以获得具有所有Client详细信息和功能的Person的客户端版本。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句