Polymorphism in Django

前端 未结 8 982
死守一世寂寞
死守一世寂寞 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:49

    This is a little ugly, but I think it should work:

    entities = Entity.objects.all()
    for entity in entities:
       try:
           print entity.team
       except:
           print entity.athlete
    

    Check out http://docs.djangoproject.com/en/1.0/topics/db/models/#id7 for more on multi-table inheritance. Just be careful, because the Django ORM is inevitably a leaky abstraction and things you might normally do with objects can get you in trouble, or do unexpected things.

提交回复
热议问题