Aleksa Rajković
Aleksa Rajković

Reputation: 83

Check if each value within list is present in the given Django Model Table in a SINGLE query

So let's say I want to implement this generic function:

def do_exist(key:str, values:list[any], model: django.db.models.Model) -> bool

Which checks if all the given values exist within a given model's column named key in a SINGLE query. I've implemented something like this

from django.db.models import Exists
def do_exist(key, values, model):
    chained_exists = (Exists(model.objects.filter(F(key)=value)) for value in values)
    qs = model.objects.filter(*chained_exists).values("pk")[:1] 
    # Limit and values used for the sake of less payload
    return len(qs) > 0

It generates a pretty valid SQL query, but the thing that scares me is that if I try to append evaluating method call to qs like .first() instead of [:1] or .exists() MYSQL connection drops. Does anyone have a more elegant way of solving this?

Upvotes: 3

Views: 5523

Answers (3)

ulduz
ulduz

Reputation: 119

res = MyModel.objects.filter(id__in=pks)

Upvotes: 0

Chymdy
Chymdy

Reputation: 660

qs = MyModel.objects.filter(id__in=pks)

This gives you a queryset that you can apply .all() etc to

Upvotes: 1

AKX
AKX

Reputation: 169051

If you know you're passing in N pks, then a count() query filtered by those pks should have exactly N results.

def do_exist(model, pks):
    return model.objects.filter(pk__in=pks).count() == len(pks)

Upvotes: 7

Related Questions