How to use python 'in' operator with generator class queryset results in function?

Viewed 41

I need to check if a <class 'str'> value exists in a list generated by queryset. Now, this works perfectly when used in a view.

my_string = 'Granny Smith'
my_query = Orchard.objects.all().values_list('apples', flat=True).iterator()
if my_string in my_query:
    print('This works ok', type(my_string), type(my_query))
    # Print: 'This works ok, <class 'str'>, <class 'generator'>

The problem occurs, when I try to pass queryset results as a parameter in a function:

def my_function(queryset_data):
    other_string = 'Granny Smith'
    if other_string in queryset_data:
       print('There is Belle de Boskoop in my q results.', type(other_string), type(queryset_data))

Am I passing the queryset results from the view correctly or are class generator values not meant to be used this way?

The reason why I am using iterator(): I need a lightning-fast, cache-less query, every delay hurts my app. By using iterator(), there is no repeated query or caching as stated in documentation https://docs.djangoproject.com/en/4.1/ref/models/querysets/#django.db.models.query.QuerySet.iterator.

1 Answers

If you just want to check if there is any record with matching string then you can just use:

my_string = 'Granny Smith'

# query of all Orchard record with apples='Granny Smith'
my_query = Orchard.objects.filter(apples=my_string)

# check if any record exists. Returns boolean
is_record_found = my_query.exists()
Related