Django使用自定义排序规则进行查询

Django使用自定义排序规则进行查询

问题描述:

是否可以使用与数据库表不同的排序规则进行查询?

Is it possible to make query with a collation different from database table have?

以下是如何使用指定排序规则,而不是给定表/列的默认排序规则。我假设您一直希望utf8_general_ci不区分大小写,但是您可以轻松地在代码中更改它或将其添加为变量。

Here is how you can use a specific collation instead of the default collation for a given table/column. I'm assuming you always want that to be the case insensitive utf8_general_ci, but you can easily change that in the code or add it as a variable.

请注意参数kwarg而不是db文字函数。参数存在的目的完全相同。

Note the use of the params kwarg instead of the db literal function. Params exists for the exact same purpose.

def iexact(**kw):
    fields = [['%s=%%s collate utf8_general_ci'%field,value] for (field,value) in kw.items()]
    return dict(where=[f[0] for f in fields], params=[f[1] for f in fields])

if User.objects.extra(**iexact(username='joeblow')).exists():
    status = "Found a user with this username!"