Skip to content
Advertisement

Python returning false on checking if a string exists in list even when it does

I imported a model(named Feature) and set it to a list in Django

posts = Feature.objects.order_by('name') 

upon calling the 5th element print(posts[5]) this displays apple in shell which is the 5th object however on checking it with a if condition it returns false

if 'apple' in posts:
    print("yes")
else:
    print("no")

and it prints no .. why is this happening even tho apple exists in the list

Advertisement

Answer

'apple' is a string object. posts is not a list but QuerySet object of Feature objects. It will never find object of other type :)

You have to seek Feature objects like that, in example:

apple = Feature.objects.get(name='apple')
# or if you have more than one
apple = Feature.objects.filter(name='apple').first()

posts = Feature.objects.order_by('name') 

if apple in posts:
    print("yes")
else:
    print("no")

it will print yes.

PS If name is going to be unique you can add unique=True to the model.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement