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

Time:06-17

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

CodePudding user response:

'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.

CodePudding user response:

I think you need to just run queryset

  1. for if the string is Case-insensitive
    fruit = "apple"     
    posts = Feature.objects.filter(name__icontains = "apple")
    if posts.exists():
       print("yes")
    else:
       print("No")
  1. for Case-insensitive exact match
        fruit = "apple"
        posts = Feature.objects.filter(name__iexact= "apple")
        if posts.exists():
           print("yes")
        else:
           print("No")
  • Related