如何使用 Django 中的相关名称从两个与第三个 table 有关系的不同 table 获取 objects?

How to get objects from two different tables that have a relationship to a third table using the related names in Django?

让我解释一下。我有 2 个 table 是另一个摘要 table 的 child class。摘要 table 与名为 Foo 的模型有关系。 related_name 是动态设置的。代码如下所示:

class Foo(models.Model):
    ...

class Parent(models.Model):
    foo = models.ForeignKey(
        Foo,
        on_delete=models.CASCADE,
        related_name='%(app_label)s_%(class)s_related'
    )
    ...

    def bar(self):
        print('bar')

    class Meta:
        abstract = True

class ChildOne(Parent):
    ...

class ChildTwo(Parent):
    ...

因此,相关的名称变为'myapp_childone_related''myapp_childtwo_related'

现在,假设我想从与 [=] 相关的 ChildOneChildTwo 模型中调用所有 object 的 bar() 方法14=] object。不过有一个问题,我想使用 Foo 模型的 class 方法。目前,我是这样做的:

 class Foo(models.Model):
     ...

     def call_bar(self):
         references = ('childone', 'childtwo')
         for ref in references:
             children = getattr(self, f'myapp_{ref}_related').all()
             for child in children:
                 child.bar()

这很好用,但老实说感觉有点 hack-y,尤其是在处理超过两个 children class 时。这个问题有更好、更 Pythonic 的解决方案吗?

编辑:我决定之前不提我想从 Foo 模型的 class 方法中调用 bar() 方法,因为我认为这是不必要的这个问题。但是,Daneil Roseman 的回答建议列出 classes,这是一个很好的解决方案,但它在 class 方法中不起作用,因为 classes 尚未定义在模块中的那个点。所以在这次编辑中提到这一点。

A related_name 只是用于从相关 class 本身执行查询的语法糖。所以你应该明确地这样做:

child_classes = [ChildOne, ChildTwo]
for child_class in child_classes:
    children = child_class.objects.filter(foo=foo)