當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Django StrIndex用法及代碼示例

本文介紹 django.db.models.functions.StrIndex 的用法。

聲明

class StrIndex(string, substring, **extra)

返回一個正整數,對應於 substringstring 內第一次出現的 1 索引位置,如果未找到 substring,則返回 0。

使用示例:

>>> from django.db.models import Value as V
>>> from django.db.models.functions import StrIndex
>>> Author.objects.create(name='Margaret Smith')
>>> Author.objects.create(name='Smith, Margaret')
>>> Author.objects.create(name='Margaret Jackson')
>>> Author.objects.filter(name='Margaret Jackson').annotate(
...     smith_index=StrIndex('name', V('Smith'))
... ).get().smith_index
0
>>> authors = Author.objects.annotate(
...    smith_index=StrIndex('name', V('Smith'))
... ).filter(smith_index__gt=0)
<QuerySet [<Author: Margaret Smith>, <Author: Smith, Margaret>]>

警告

在 MySQL 中,數據庫表的排序規則確定字符串比較(例如該函數的expressionsubstring)是否區分大小寫。默認情況下,比較不區分大小寫。

相關用法


注:本文由純淨天空篩選整理自djangoproject.com大神的英文原創作品 django.db.models.functions.StrIndex。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。