简体   繁体   English

使用Python中的方法区分大小写

[英]Case insensitive search using a method in Python

I have a method called get_obj_or_none which returns an object or none. 我有一个名为get_obj_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 我在变量song_name获取Song对象的歌曲名称

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

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

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

Pass name__iexact instead of name . 传递name__iexact而不是name

The documentation is here 文档在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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