Polymorphism in Django

前端 未结 8 908
死守一世寂寞
死守一世寂寞 2021-01-07 06:11

I have the following models. How do I get access to the unicode of the inheriting tables (Team and Athete) from the Entity table? I\'m trying to display a l

8条回答
  •  迷失自我
    2021-01-07 06:59

    I don't believe you have to do anything. If Entity is never instantiated directly, you will never call the non-existent Entity.__unicode__ method. However, if you'd like to play it save, you could add a stub method in your Entity class:

    class Entity(models.Model):
    
        def __unicode__(self):
            pass
    
    class Team(Entity):
    
        def __unicode__(self):
            return self.name
    
    class Athlete(Entity):
    
        def __unicode__(self):
            return '%s %s' % (self.firstname, self.lastname)
    

    You are now assured that any class which inherits from Entity will have a __unicode__ method, and you can simply traverse them:

    for thing in [TeamA(), AthleteA(), TeamB(), AthleteB()]:
        print unicode(thing)
    

提交回复
热议问题