I have an instance of a model. I have a queryset. Can I check if the instance matches a filter without filtering all model objects?

Situation: I have a model Alpha, when this model is created I need to check if it matches a user defined filter which is stored in model Bravo. There will be many Alpha models and many Bravo models (filters).

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"

My assumption is

if a in Alpha.objects.filter(bravo.get_qs())

Will filter all Alpha objects. I don't want this because I don't need to check any other instances apart from "a" and there will be a lot. I don't want to check all Alpha objects for each Bravo object.

I am open to other suggestions on how I might go about doing something similar to the above.

1 Answers

Oluwafemi Sule On Best Solutions

Instead of a in Alpha.objects.filter(bravo.get_qs()), you can check that a queryset having same primary key as a exists in 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"