简体   繁体   中英

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?

您可以通过以下方式进行案例敏感匹配

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

Pass name__iexact instead of name .

The documentation is here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM