姜戈:如何获取多条过滤查询最相似的记录 [英] Django: How to get the most similar record to multi filter query

查看:28
本文介绍了姜戈:如何获取多条过滤查询最相似的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个消费品数据库,我需要根据他们的规格过滤。这些查询可以过滤多达10种不同类型的字段。这通常不会导致完全匹配。当没有完全匹配的产品时,我想退回最相似的产品。我认为最简单的方法是为与过滤匹配的每一列添加注释。然后按数量最多的产品订购。有什么办法可以做到这一点吗?或者,有没有其他方法可以与Django获得类似的匹配?

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

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

如果查询集为空,我希望返回这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())
)

然后,查询集中的每一行都将使用匹配列数进行批注,这可用于过滤或ORDER BY

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

这篇关于姜戈:如何获取多条过滤查询最相似的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆