简体   繁体   中英

Exclude a queryset from bigger queryset in django without hitting the database

I have a queryset of all objects of a model. Iterating over the objects, I am removing updating rows with value repetition in a column. So without having to hit the database again, i want to remove the updated rows from the bigger queryset.

What is the most efficient way to do this?

You may need to provide more information about your specific use case, but in general, Django defers the evaluation of QuerySets until they are actually needed. If you are able to construct a QuerySet of the exclusion set independently of the larger QuerySet, you can call the .exclude() method and generate one large query instead of two smaller ones. For example:

excluded_set = Model.objects.filter(...)
large_set = Model.objects.filter().exclude(id__in=excluded_set)

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