【问题标题】:ValueError when including both strings and integers in django.db.models.Q search string在 django.db.models.Q 搜索字符串中同时包含字符串和整数时出现 ValueError
【发布时间】:2021-02-08 06:28:19
【问题描述】:

我有以下函数,它应该接受 3 个参数(标题、描述或产品 ID)。前两个是字符串,第三个是整数值。

# Create the necessary search function for assignment
def search(request):  # Get all products below where title, desc or product ID is in the query
    query = request.GET.get('query')
    products = Product.objects.filter(Q(title__icontains=query) | Q(description__icontains=query) | Q(product_id=query))

    context = {
        'query': query,
        'products': products
    }

上述函数抛出错误:

ValueError at /search/
Field 'product_id' expected a number but got 'playstation'.
Request Method: GET
Request URL:    http://localhost:8000/search/?query=playstation
Django Version: 3.1.2
Exception Type: ValueError
Exception Value:    
Field 'product_id' expected a number but got 'playstation'.

搜索栏将只接受整数值。是否可以在 Q 对象中包含同时使用字符串或整数的选项?我对 MySQL 语法很陌生。

【问题讨论】:

    标签: python search django-models integer valueerror


    【解决方案1】:

    product_id 仅对整数有意义。所以你不能用一个字符串来查询。

    你可以检查它是否是一个数字序列,然后将其转换为一个int:

    def search(request):
        query = request.GET.get('query')
        qs = Q(title__icontains=query) | Q(description__icontains=query)
        if query.isdigit():
            qs |= Q(product_id=query)
        products = Product.objects.filter(qs)
    
        context = {
            'query': query,
            'products': products
        }
        # …

    【讨论】:

    • 哇,这很完美。比花将近 2 个小时才意识到我不能将 MySQL 的“OR”术语包含在语句中要简单得多。祝福你的灵魂,享受咖啡。
    猜你喜欢
    • 2023-02-13
    • 2011-05-25
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 2013-06-26
    • 2013-11-10
    • 2018-06-23
    相关资源
    最近更新 更多