这从卡尔·迈耶答案由保罗·麦克米兰前面提到的问题可能是你在找什么。在某些答案中未解决的这个问题的一个微妙之处是如何从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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)