Home > database >  Django: Search products starting with query => product_name__starswith=query
Django: Search products starting with query => product_name__starswith=query

Time:01-11

Products model

class Products(models.Model):
    product_name = models.CharField(max_length=120)

Queryset

Products.objects.filter(product_name__startswith=query)

I want to find all the products starting with search query only.

For example: When I search for ca it returns

car
car cover

and when I search for car cover, it only returns

car cover

But I want it to return car in the second search as well. Is there any possible way to do it? Please help me. Thank you.

CodePudding user response:

Please try below, it may help:

Products.objects.filter(product_name__contains=query)

Here it will search whether "query" is there anywhere in the product_name.

CodePudding user response:

You can do it by annotating your searched string literal with Value and using it with F:

# `query` supposed given

products = Products.objects.annotate(
    query=Value(query, output_field=CharField())
).filter(
    query=F("product_name")
).all()
  •  Tags:  
  • Related