Django:如何获取最相似的记录以进行多过滤器查询

Django: How to get the most similar record to multi filter query

我有一个消费品数据库,我需要根据它们的规格进行过滤。这些查询可以过滤超过 10 种不同类型的字段。这通常会导致不完全匹配。当没有完全匹配时,我想 return 最相似的产品。我认为最简单的方法是为与过滤器匹配的每一列注释“计数”。然后按具有最大“计数”的产品排序。有没有办法做到这一点?或者有其他方法可以与 Django 进行类似的匹配吗?

例如,如果我有以下查询:

Laptop.objects.filter(brand='Dell', ram=8, price__lte=1000, screen_size=13.3)

如果查询集为空,我想 return 具有这 4 个过滤器中最匹配字段的笔记本电脑。

我遇到的一个“丑陋”的解决方案是将多个调用链接到 annotate(),为每个匹配递增相同的注释

from django.db.models import Value, F, Case, When, IntegerField

annotated_laptops = Laptop.objects.annotate(
    matches=Value(0)
).annotate(
    matches=Case(When(brand='Dell', then=F('matches') + 1), default=F('matches'), output_field=IntegerField())
).annotate(
    matches=Case(When(ram=8, then=F('matches') + 1), default=F('matches'), output_field=IntegerField())
).annotate(
    matches=Case(When(price__lte=1000, then=F('matches') + 1), default=F('matches'), output_field=IntegerField())
).annotate(
    matches=Case(When(screen_size=13.3, then=F('matches') + 1), default=F('matches'), output_field=IntegerField())
)

然后,查询集中的每一行都将用匹配列的数量进行注释,这可用于过滤或排序

laptops = annotated_laptops.filter(matches=4)
if laptops.count() == 0:
    laptops = annotated_laptops.order_by('-matches')