加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:28:51 所属栏目:Python 来源:网络整理
导读:我有一个模型人员,存储有关人员的所有数据.我还有一个扩展Person的客户端模型.我有另一个扩展模型OtherPerson,它也扩展了Person模型.我想创建一个指向Person的客户端,并且还创建一个指向该Person的OtherPerson记录.基本上,我希望将一个Person对象视为Client
我有一个模型人员,存储有关人员的所有数据.我还有一个扩展Person的客户端模型.我有另一个扩展模型OtherPerson,它也扩展了Person模型.我想创建一个指向Person的客户端,并且还创建一个指向该Person的OtherPerson记录.基本上,我希望将一个Person对象视为Client和OtherPerson,具体取决于当前视图.这是否可以使用Django的ORM,或者我是否需要以某种方式编写Raw查询来创建此场景.我非常确定它可以从数据库端进行,因为两个子类只会指向具有person_ptr_id字段的父Person类.

简单地说,如果我创建一个客户端(以及一个Person),我还可以使用客户端的基本Person创建一个OtherPerson对象.这样我可以将它们视为客户端或者作为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,help_text="Middle Name.")
    last_name = models.CharField(db_index=True,help_text="Last Name.")
    alias = models.CharField(db_index=True,max_length=128,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 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()

如果我有一个现有的客户端并希望从他们那里创建一个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.我可以获得具有所有OtherPerson详细信息和功能的Person的OtherPerson版本,或者我可以获得具有所有客户端详细信息和功能的该Person的客户端版本.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读