gpt4 book ai didi

python - 如何连接表django模型的两列

转载 作者:太空狗 更新时间:2023-10-29 20:46:55 24 4
gpt4 key购买 nike

我正在我的项目中实现搜索,我想要的是连接到 where 子句中的列以从表中获取结果。

这是我正在做的:

from django.db.models import Q

if 'search[value]' in request.POST and len(request.POST['search[value]']) >= 3:
search_value = request.POST['search[value]'].strip()

q.extend([
Q(id__icontains=request.POST['search[value]']) |
(Q(created_by__first_name=request.POST['search[value]']) & Q(created_for=None)) |
Q(created_for__first_name=request.POST['search[value]']) |
(Q(created_by__last_name=request.POST['search[value]']) & Q(created_for=None)) |
Q(created_for__last_name=request.POST['search[value]']) |
(Q(created_by__email__icontains=search_value) & Q(created_for=None)) |
Q(created_for__email__icontains=search_value) |
Q(ticket_category=request.POST['search[value]']) |
Q(status__icontains=request.POST['search[value]']) |
Q(issue_type__icontains=request.POST['search[value]']) |
Q(title__icontains=request.POST['search[value]']) |
Q(assigned_to__first_name__icontains=request.POST['search[value]']) |

])

现在我想添加另一个 OR 条件,例如:

CONCAT(' ', created_by__first_name, created_by__last_name) like '%'search_value'%'

但是当我将这个条件添加到查询集中时,它变成了 AND

where = ["CONCAT_WS(' ', profiles_userprofile.first_name, profiles_userprofile.last_name) like '"+request.POST['search[value]']+"' "]
tickets = Ticket.objects.get_active(u, page_type).filter(*q).extra(where=where).exclude(*exq).order_by(*order_dash)[cur:cur_length]

如何将其转换为 OR 条件?

最佳答案

高级过滤器可以解决 Q() objectQuery expressions比如 Func()、Value() 和 F()。唯一使用的技巧是 Custom Lookup “rhs_only”使用查找的右侧并忽略左侧,因为直接在右侧使用所有串联字段更容易。一个令人难忘的函数 concat_like 封装了所有这些以便在查询中轻松使用。

from django.db.models import F, Func, Lookup, Q, Value
from django.db.models.fields import Field

def concat_like(columns, pattern):
"""Lookup filter: CONCAT_WS(' ', column_0, column_1...) LIKE pattern"""
lhs = '%s__rhs_only' % columns[0]
expr = Func(*(F(x) for x in columns), template="CONCAT_WS(' ', %(expressions)s)")
return Q(**{lhs: Like(expr, Value(pattern))})

class Like(Func):
def as_sql(self, compiler, connection):
arg_sql, arg_params = zip(*[compiler.compile(x) for x in self.source_expressions])
return ("%s LIKE '%s'" % tuple(arg_sql)), arg_params[0] + arg_params[1]

@Field.register_lookup
class RhsOnly(Lookup):
"""Skip the LHS and evaluate the boolean RHS only"""
lookup_name = 'rhs_only'

def as_sql(self, compiler, connection):
return self.process_rhs(compiler, connection)

此代码支持所有 bool 表达式和相关对象。所有参数均已正确转义。

示例用法:

>>> qs = MyModel.objects.filter(Q(id=1) | concat_like(('first_name', 'surname'), 'searched'))
>>> str(qs.query) # sql output simplified here
"SELECT .. WHERE id=1 OR (CONCAT_WS(' ', first_name, surname) LIKE 'searched')"

关于python - 如何连接表django模型的两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44968640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com