Django:是否可以在不过滤所有模型实例的情况下检查模型实例是否与过滤器匹配

时间:2019-04-23 19:16:39

标签: python django django-models filter django-queryset

我有一个模型实例。我有一个查询集。是否可以在不过滤所有模型对象的情况下检查实例是否与过滤器匹配?

情况: 我有一个模型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”外,我不需要检查其他任何实例,并且会有很多实例。我不想为每个Alpha对象检查所有Bravo个对象。

我愿意就如何做与上述类似的事情提出其他建议。

1 个答案:

答案 0 :(得分:1)

您可以检查与a in Alpha.objects.filter(bravo.get_qs())中的a exists具有相同主键的查询集,而不是Alpha

alpha = Alpha.objects.filter(pk=a.pk)

for bravo in Bravo.objects.all():
    if alpha.filter(bravo.get_qs()).exists():
        # Do something with "a" depending on which "b"