【发布时间】:2019-09-13 00:56:43
【问题描述】:
我有一个模型实例。我有一个查询集。我可以在不过滤所有模型对象的情况下检查实例是否匹配过滤器吗?
情况:
我有一个模型Alpha,创建此模型时我需要检查它是否与存储在模型Bravo 中的用户定义过滤器匹配。会有很多Alpha 模型和很多Bravo 模型(过滤器)。
class Alpha(models.Model):
test = models.CharField()
class Bravo(models.Model):
test = models.CharField()
def get_qs(self):
# These could be longish and complex, defined by users
return Q(test=self.test) | Q(test=f"{self.test}a")
# There will be many of these but I only want to check this instance
a = Alpha(test="testa")
# There will be many of these, I need to check if queries from get_qs match "a"
b = Bravo(test="test")
# Lots of Bravo, all need to be checked, unavoidable
for bravo in Bravo.objects.all():
# Lots of Alpha, don't want to check them all
# Just check "a" matches bravo.get_qs filter
if a in Alpha.objects.filter(bravo.get_qs()):
# Do something with "a" depending on which "b"
pass
我的假设是
if a in Alpha.objects.filter(bravo.get_qs())
将过滤所有Alpha 对象。我不想要这个,因为我不需要检查除“a”之外的任何其他实例,而且会有很多。我不想检查每个 Bravo 对象的所有 Alpha 对象。
我愿意接受其他关于如何做与上述类似的事情的建议。
【问题讨论】:
标签: python django django-models filter django-queryset