How do I filter search results based off their closeness to a search string in with querysets

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.

Welcome @DuggyWantsYourSoul87 !

Technically, this isn’t an accurate statement. It would be more accurate to say that you’re requesting the results in whatever order the database engine wishes to return them to you. The engine is free to return the results in any order.

You don’t identify which database engine, so we can’t specifically identify why you’re seeing the results in a specific order, but I would guess that there’s a good chance these results are being returned to you in order of the primary key.

There is no concept of “relevance” in the query you have defined. You would need to set your database up with the proper structure to support this. It’s not something automatically provided.

1 Like