简体   繁体   中英

Make sure all list items based on fields exists in table efficiently

I have a model like this:

class MyModel(models.Mode):
    foo = models.CharField(...)
    bar = models.CharField(...)

and I have a list contains foo and bar field values. I want to check all of items in this list, exists in the database. For example:

my_list = [{'foo': 'foo_1','bar': 'bar_1'}, {'foo': 'foo_2','bar': 'bar_2'}]

I want to check all records exists values corresponding to the list items fields in the database. I can change my list structure.

I can do it with for loop but I want to find more efficient way. Is it possible with single query?. Is there any suggestion?

You can try to check the number of instances from SQL response:

from django.db.models import Q

my_list = [{'foo': 'foo_1','bar': 'bar_1'}, {'foo': 'foo_2','bar': 'bar_2'}]
query = Q()
for i in my_list:
    query &= Q(foo=i['foo'], bar=i['bar'])
queryset = MyModel.objects.filter(query)

assert queryset.count() == len(my_list)  # 2 == 2

So in case you have all values in your DB the count and len values will be same.

in case your my_list includes only proper fields you can do just:

for i in my_list:
    query &= Q(**i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM