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

Django:两个不同的子类指向同一个父类,第1张

概述我有一个模型人员,存储有关人员的所有数据.我还有一个扩展Person的客户端模型.我有另一个扩展模型OtherPerson,它也扩展了Person模型.我想创建一个指向Person的客户端,并且还创建一个指向该Person的OtherPerson记录.基本上,我希望将一个Person对象视为Client和OtherPerson,具体取决于当前视图.这是否可以使用Django的ORM,或者我是否需要 我有一个模型人员,存储有关人员的所有数据.我还有一个扩展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的客户端版本.

总结

以上是内存溢出为你收集整理的Django:两个不同的子类指向同一个父类全部内容,希望文章能够帮你解决Django:两个不同的子类指向同一个父类所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1192904.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存