Reputation: 2535
In my Django project I need to check whether a user submitted value exists in a list of values that is returned from the database via objects.filter().
User submitted data:
value = request.data['value_id']
Get valid status as ids:
allowed_values = Values.objects.filter(Q(code='Active') | Q(code='Inactive')).values('id')
This returns a queryset as follows.
<QuerySet [{'id': 1}, {'id': 2}]>
Checking if user submitted value exists in the allowed_values:
if value in allowed_values:
return True
But this does not work and I need allowed_values to return as a list of 'id's. How can I do this without iterating through allowed_values and creating a new list?
Upvotes: 2
Views: 10333
Reputation: 1394
As per your code, you can write solve it as below logic...
allowed_values = Values.objects.filter(Q(code='Active') | Q(code='Inactive')).values('id')
allowed_values_list = list(allowed_values)
for id_dict in allowed_values_list
if value == id_dict['id']:
return True
Upvotes: 0
Reputation: 15431
You can use exists(), as simple as
allowed_values = Values.objects.filter(...).exists()
This will return True if the QuerySet contains any results.
Upvotes: 1
Reputation: 2627
You can use values_list() method instead of values() method
allowed_values = Values.objects.filter(Q(code='Active') | Q(code='Inactive')).values_list('id',flat=True)
Or, if you need only checking, you can use filter :
if Values.objects.filter(Q(code='Active') | Q(code='Inactive')).filter(id=value).count() > 0:
return True
Upvotes: 3