Unknown Coder
Unknown Coder

Reputation: 813

Case insensitive search using a method in Python

I have a method called get_obj_or_none which returns an object or none.

def get_obj_or_none(model, **kwargs):
    try:
        return model.objects.get(**kwargs)
    except model.DoesNotExist:
        return None

I'm getting the song name of a Song object in the variable song_name

I'm adding new objects as follows

if not get_obj_or_none(Song, name=song_name, artist=dj):
    s = Song(name=song_name, artist=dj, release_date=song['releaseDate'])
    s.save()

How can I do a case insensitive search in the get_obj_or_none method without adding a lower case song_name to the object's song name?

Upvotes: 0

Views: 89

Answers (2)

Sam Mussmann
Sam Mussmann

Reputation: 5993

Pass name__iexact instead of name.

The documentation is here

Upvotes: 0

dm03514
dm03514

Reputation: 55962

you could do a case insesitive match by

get_obj_or_none(Song, name__iexact=song_name, artist=dj)

Upvotes: 1

Related Questions