django - 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
推荐阅读
- javascript - 表格填写excel电子表格
- python - 优化mysql多次更新
- mysql - mySQL 用特定列连接同一张表
- python - 通过在python中分组值的条形图
- javascript - JQuery - 不切换类
- javascript - 将 Node 应用程序中的所有音频保存到 mp3,然后将其直播到直播服务器
- c++ - 为什么 g++ 编译器在我的 cpp 文件中的每个字符之间添加空格?
- javascript - AJAX 用于重用不同的数据?(没有 jQuery)
- node.js - Firebase 云消息命中错误
- c# - WCF Rest - 传入camelCase Json到PascalCase对象