Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading