Django 反向包含/icontains [英] Django reverse to contains/icontains

查看:36
本文介绍了Django 反向包含/icontains的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题解决了反向LIKE操作,例如如果字段名称是Peter Johnson",我们可以通过这样的查询找到它:

In this question was solved problem for reverse LIKE operation in SQL, for example if field name is "Peter Johnson", we could find it by such query:

select name from user where "Mr. Peter Johnson" like CONCAT('%', name, '%')

有没有办法在 Django Q 对象中做这样的事情(我正在构建一个大查询,所以使用原始 SQL 查询是不合理的)?

Is there any way to do such thing in Django Q object (I'm building a big query, so using raw SQL query will not be rational)?

推荐答案

虽然 extras 确实为边缘情况提供了扩展的复杂功能,但 extras 应该被视为最后的手段,并且可能会在某些时候被弃用.

While extras do provide an expanded complex functionality for edge cases, extras should be treated as last resort and likely going to be deprecated at some point.

这可以使用注释和过滤来完成.

This can be accomplished using annotate and filtering.

from django.db.models import F, Value, CharField

MyUserModel.objects 
     .annotate(my_name_field=Value('Mr. Peter Johnson', output_field=CharField())) 
     .filter(my_name_field__icontains=F('name'))

泛化:

from django.db.models import F, Value, CharField

@staticmethod
def reverse_case_insensitive_contains(model, search_field_name: str, search_field_value: str):
    return model.objects 
        .annotate(search_field=Value(search_field_value, output_field=CharField())) 
        .filter(search_field__icontains=F(search_field_name))

这篇关于Django 反向包含/icontains的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆