首页 > 解决方案 > Django - 通过外来对象查找所有相关的 OneToOneField 对象

问题描述

抱歉,如果标题不清楚,这就是我要完成的工作:

class Document(models.Model):
    processed = models.BooleanField(default=False)

class ParentClass(models.Model)
    document = models.OneToOneField(Document, on_delete=models.SET_NULL, null=True)

    class Meta:
        abstract = True

    def do_something():
        raise NotImplementedError()

class SubclassOne(ParentClass):
    # Some fields.
    def do_something(self):
        # Something specific to this subclass

class SubclassTwo(ParentClass):
    # Some other fields.
    def do_something(self):
        # Something specific to this subclass

我的第一个想法是尝试通过ParentClass

ParentClass.objects.filter(document__processed=False)

但这不起作用,因为父类是abstract.

现在我尝试通过Document对象

Document.objects.filter(processed=False)

但似乎没有办法通过每个个体查找相关对象Document。我不确定这是否是一个好的解决方案,因为 与 的紧密耦合,ParentClass不需要Document知道ParentClass' 的实现。

标签: djangodjango-modelsormone-to-one

解决方案


您可以找到所有反向相关的字段名称,并可以循环如下:

documents = Document.objects.filter(processed=False)
reverse_related_fields = Document._meta.get_fields()

for document in documents:
    for reverse_related_field in reverse_related_fields:
        if reverse_related_field.one_to_one:
            attr = getattr(document, f"{reverse_related_field.name}_set")
            try:
                attr.get().do_something
            except Exception:
                pass

推荐阅读