Django ORM搜索多个条件查询

时间:2019-07-03 09:06:10

标签: django django-orm

当我要使用多个条件搜索查询集时遇到问题。在我的数据库中,hscode保存为"0105.14.90"。我需要按照以下查询"01051490"搜索hscode。例如:

>>> query = '0105.14.90'
>>> HSCode.objects.filter(hscode=query)
<QuerySet [<HSCode: 0105.14.90>]>


>>> query = '01051490'
>>> HSCode.objects.filter(hscode=query)
<QuerySet []>

我认为我可以做的坏事是这样的:

hscodes = []
query = '01051490'

for hscode in HSCode.objects.order_by('-id'):
    if query.isdigit() and hscode.hscode == query:
        hscodes.append(hscode)

    elif hscode.hscode.replace('.', '') == query:
        hscodes.append(hscode)

仅使用 ORM 怎么处理?

>>> query = '01051490'
>>> HSCode.objects.filter(Q(hscode=query) | Q(???))
<QuerySet [<HSCode: 0105.14.90>]>

1 个答案:

答案 0 :(得分:1)

您可以尝试使用Replace

from django.db.models import Value
from django.db.models.functions import Replace

query = '01051490'
HSCode.objects.annotate(
    hscode_without_dots=Replace('hscode', Value('.'), Value(''))
).filter(hscode_without_dots=query)