pythonsearchdjango-modelsintegervalueerror

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


I have the following function which should take 3 arguments (either title, description or product_id). The first two are strings and the third is an integer value.

# 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
    }

The above function throws an error:

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'.

The search bar will accept only an integer value. Is it possible to include the option of using both strings or integers with the Q object? I'm very new to MySQL synatax.


Solution

  • product_id is only sensical for integers. So you can not query with a string for that.

    You can check if it is a sequence of digits, and then convert it to an 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
        }
        # …