在 django.db.models.Q 搜索字符串中同时包含字符串和整数时出现 ValueError

ValueError when including both strings and integers in django.db.models.Q search string

我有以下函数,它应该有 3 个参数(标题、描述或 product_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 object 中包含同时使用字符串或整数的选项?我对 MySQL 语法很陌生。

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

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

def search(request):
    query = request.GET.get('query')
    <b>qs =</b> Q(title__icontains=query) | Q(description__icontains=query)
    if <b>query.isdigit()</b>:
        qs |= Q(product_id=query)
    products = Product.objects.filter(<b>qs</b>)

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