Polymorphism in Django

前端 未结 8 909
死守一世寂寞
死守一世寂寞 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条回答
  •  -上瘾入骨i
    2021-01-07 06:56

    I answered a similar question a while ago. Have a look, I think one of the answers probably solves your problem as well.

    How do I access the child classes of an object in django without knowing the name of the child class?

    My answer from there was to add this to the parent class:

    def get_children(self):
        rel_objs = self._meta.get_all_related_objects()
        return [getattr(self, x.get_accessor_name()) for x in rel_objs if x.model != type(self)]
    

    Then you can call that function to get the children objects (in your case you will only have one) and then call the unicode function from that object.

提交回复
热议问题