Skip to main content
 首页 » 编程设计

python之Django 中的多态性

2025年05月04日29Renyi-Fan

我有以下型号。如何从实体表访问继承表(Team 和 Athete)的 unicode?我正在尝试显示所有实体的列表,如果是团队,则显示“姓名”,如果是运动员,则显示“名字”和“姓氏”。

class Entity(models.Model): 
  entity_type_list = (('T', 'Team'), ('A', 'Athlete')) 
  type = models.CharField(max_length=2, choices=entity_type_list,default='P')  
  pictureurl = models.URLField('Picture Url', verify_exists=False, max_length=255, null=True, blank=True) 
 
 
class Team(Entity): 
 
  name = models.CharField(max_length=100) 
 
  def __unicode__(self): 
    return self.name 
 
class Athlete(Entity): 
 
  firstname = models.CharField(max_length=100) 
  lastname = models.CharField(max_length=100) 
 
  def __unicode__(self): 
    return '%s %s' % (self.firstname, self.lastname) 

请您参考如下方法:

这answer from Carl Meyer Paul McMillan 之前提到的问题可能就是您要找的。一些答案中没有捕捉到这个问题的一个微妙之处是如何从实体上的 QuerySet 获取派生类实例。

问题

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

解决方案

在上面链接的答案中使用 InheritanceCastModel 混合作为实体的基类。然后,您可以从 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 info 
 
class Athlete(Entity): 
  # unchanged 
 
class Team(Entity): 
  # unchanged 
 
for entity in Entity.objects.all(): 
  actual_entity = entity.cast() 
  print unicode(actual_entity) # actual entity is a a Team or Athlete