[Django]-Django, check if exists but on many items from an array of properties

4👍

Based on your comment, the items in arr all have a distinct id, so we can count the number of items that satisfy this condition. We know that this should be the same as the number of dictionaries in arr, since each Q(id=..., ...) can satisfy at most one record:

from functools import reduce
from operator import or_

MyTable.objects.filter(
    reduce(or_, [Q(id=n['id'],filename=n['filename']) for n in arr])
).count() == len(arr)

2👍

Make a list of all the ids and filenames, then use __in
https://docs.djangoproject.com/en/2.2/ref/models/querysets/#in

ids = [item.get('id') for item in arr]
filenames = [item.get('filename') for item in arr]
qs = MyTable.objects.filter(id__in=ids, filename__in=filenames)
assert qs.count() == len(arr)

Leave a comment