Teshan N.
Teshan N.

Reputation: 2535

Django: Check if value exists in object.filter list

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

Answers (4)

Manan M.
Manan M.

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

Tiago Peres
Tiago Peres

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

kamilyrb
kamilyrb

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

weAreStarsDust
weAreStarsDust

Reputation: 2742

use values_list('id', flat=True) instead .values('id')

Upvotes: 1

Related Questions