在通过相关字段进行过滤时,如何应用来自自定义管理器查询集的注释和过滤器?这里有一些代码可以证明我的意思。
经理和模特
from django.db.models import Value, BooleanField
class OtherModelManager(Manager):
def get_queryset(self):
return super(OtherModelManager, self).get_queryset().annotate(
some_flag=Value(True, output_field=BooleanField())
).filter(
disabled=False
)
class MyModel(Model):
other_model = ForeignKey(OtherModel)
class OtherModel(Model):
disabled = BooleanField()
objects = OtherModelManager()
正在尝试使用管理器过滤相关字段
# This should only give me MyModel objects with related
# OtherModel objects that have the some_flag annotation
# set to True and disabled=False
my_model = MyModel.objects.filter(some_flag=True)
如果您尝试上面的代码,您将收到以下错误:
TypeError:相关字段的查找无效:some_flag
为了进一步澄清,基本上相同的问题被报告为错误,但没有回应如何实际实现这一点:https://code.djangoproject.com/ticket/26393 .
我知道这可以通过简单地直接在 MyModel
过滤器中使用来自管理器的过滤器和注释来实现,但是关键是保持这种 DRY 并确保重复这种行为 < em>无处不在访问此模型(除非明确指示不要访问)。
最佳答案
如何运行嵌套查询(或两个查询,如果您的后端是 MySQL;性能)。
第一个获取相关OtherModel
对象的pk。
第二个用于过滤获取的 pks 上的 Model
对象。
other_model_pks = OtherModel.objects.filter(some_flag=...).values_list('pk', flat=True)
my_model = MyModel.objects.filter(other_model__in=other_model_pks)
# use (...__in=list(other_model_pks)) for MySQL to avoid a nested query.
关于python - 使用相关模型的自定义管理器的 Django 过滤器相关字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44558180/