Django中的多态

Django中的多态,第1张

Django中的多态

这从卡尔·迈耶答案由保罗·麦克米兰前面提到的问题可能是你在找什么。在某些答案中未解决的这个问题的一个微妙之处是如何从Entity上的QuerySet获取派生类实例

问题

for entity in Entity.objects.all()  print unipre(entity) # Calls the Entity class unipre, which is not what you want.

一个办法

InheritanceCastModel
将上面链接的答案中的mixin用作Entity的基类。然后,您可以从Entity实例转换为实际的派生类实例。当您想在父类(实体)上使用查询集但访问派生类实例时,这特别方便。

class Entity(InheritanceCastModel):  # your model definition. You can get rid of the entity_type_list and type, as the  # real_type provided by InheritanceCastModel provides this infoclass Athlete(Entity):  # unchangedclass Team(Entity):  # unchangedfor entity in Entity.objects.all():  actual_entity = entity.cast()  print unipre(actual_entity) # actual entity is a a Team or Athlete


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

原文地址: http://outofmemory.cn/zaji/5664219.html

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

发表评论

登录后才能评论

评论列表(0条)

保存