Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 866
Aleksa Rajković Avatar asked Dec 30 '25 13:12

Aleksa Rajković


1 Answers

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)
like image 143
AKX Avatar answered Jan 01 '26 03:01

AKX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!