Issue
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?
Solution
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)
Answered By - AKX
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.