计算Djang中的\uu或\u contains lookup的匹配项数

2024-03-29 13:23:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图构建一个推荐引擎,其中一个子任务是根据从可用标记列表中匹配的VenuesVenues进行排名。在

以下是我的模型:

class Venue(TimeStampedUUIDModel):
    name = models.CharField(max_length=100, null=False, blank=False)
    tags = ArrayField(
        models.PositiveIntegerField(
            verbose_name=_('tag'), choices=TAGS_CHOICES
        ), null=True, blank=True
    )

我可以在过滤器中进行__contains查找,以确定列表中某些标记已经存在的场所。但我的动机是想知道每个场馆有多少个标签是匹配的,这样我就可以给它们分配一些等级。例如,为每个匹配的标记指定10的等级。在

因此,如果一个场所匹配说是来自tag_list的4个标签,那么它的排名应该是4*10=40。在

由于tags是一个只能包含由正数定义的选项的ArrayField,__contains查找在过滤器查询中起作用,但是我如何注释匹配的数量呢?在

最终结果可能是:

^{pr2}$

如果需要更多信息,请告诉我。在


Tags: name标记falsetrue过滤器列表modelstag
1条回答
网友
1楼 · 发布于 2024-03-29 13:23:25

所以,我使用Case来解决这个问题,它使用When条件映射到SQL案例。在

这里user_interested_in_tag_list是用户感兴趣的标签列表,其逻辑是根据与此列表匹配的标签数量对每个场所进行排名。在

from django.db.models import (
    Case, ExpressionWrapper, IntegerField, Q, Value, When
)
from functools import reduce


def calculate_user_interest_rank(venue_queryset, user_interested_in_tag_list):
    if user_interested_in_tag_list:
        # Add rank of 10 for each matched tag in the venue
        user_interest_match_query = map(
            lambda x: Case(
                When(Q(tags__contains=[x, ]), then=Value(10)), default=Value(0)
            ), user_interested_in_tag_list
        )
        user_interested_tags_matches = reduce(
            lambda x, y: x + y, user_interest_match_query
        )
        venue_queryset = venue_queryset.annotate(
            user_interest_score=ExpressionWrapper(
                user_interested_tags_matches,
                output_field=IntegerField()
            )
        )
    else:
        venue_queryset = venue_queryset.annotate(
            user_interest_score=ExpressionWrapper(
                Value(0),
                output_field=IntegerField()
            )
        )

user_interest_match_query将是When子句的列表,包括来自user_interest_match_query的每个匹配标记的Value,否则0的{}。在

user_interested_tags_matchesWhen子句的所有结果的总和,它给出了user_interest_score中注释的每个地点的实际分数。在

我希望这对某人有帮助:)如果你需要更多的细节请告诉我。在

相关问题 更多 >