Reputation: 83
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
Reputation: 660
qs = MyModel.objects.filter(id__in=pks)
This gives you a queryset that you can apply .all() etc to
Upvotes: 1
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