Hi,
So I’m working on a view that shows various products, and as I’ve been writing
a set of user filters for this view I have run into a problem with filtering with this code.
products = Product.objects.filter(
Q(name__icontains=q) & Q(category__icontains=c)
| Q(description__icontains=q) & Q(category__icontains=c))
q refers to the search query string, and c refers to the category selection.
This is supposed to be the default results with no ordering, but I end up with everything ordered by date created even though I have no default ordering set in the Product Model.
What is more annoying is when I have a search query with default ordering everything is returned alphabetized and not what’s most relevant.
For example if I search for phone, apple phone should be the second result and phone should be first, but it’s the other way around.
What’s the best way to filter objects based off what’s closest to the search query?
Here is the Product model if that helps
class Product(models.Model):
CATEGORIES = (
# Removed as not important
)
category = models.CharField(choices=CATEGORIES, null=True)
seller = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
description = models.TextField()
created = models.DateTimeField(auto_now_add=True)
price = models.FloatField()
thumbnail = models.ImageField(upload_to=get_thumbnail_filename)
def __str__(self):
return self.name
Thanks for all your help in advance.