栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Django中的多态

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/662263.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号