如何解决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
的实现。>
解决方法
您可以找到所有反向相关的字段名称,并可以循环如下:
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
,
ParentClass.objects.filter(document__processed=False)
这将返回所有已处理设置为 False
的文档。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。