如何在Python模型中循环遍历字符串



我想在模板中显示女子联盟,这是我的视图。py代码:

leagues = League.objects.all()
for league in leagues:
print(league.name)

它将向我显示所有联盟的名称,即:

International Conference of Amateur Ice Hockey
International Collegiate Baseball Conference
Atlantic Federation of Amateur Baseball Players
Atlantic Federation of Basketball Athletics
Atlantic Soccer Conference
International Association of Womens' Basketball Players
American Conference of Amateur Football
Atlantic Amateur Field Hockey League
Transamerican Womens' Football Athletics Conference
Pacific Ice Hockey Conference

我如何循环浏览这些名字,并挑选出其中有女性的联盟?

简单,使用containsicontains,因为搜索不区分大小写:

leagues = League.objects.filter(name__icontains='women')
for league in leagues:
print(league.name)

您可以在打印前检查小写的league.name是否包含"women",例如:

leagues = League.objects.all()
for league in leagues:
if "women" in league.name.lower():
print (league.name)

相关内容

  • 没有找到相关文章

最新更新