Django计数过滤注释不起作用

2024-09-27 19:27:02 发布

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

我有两个模型“ModelParent”和“ModelChild”,其中“ModelParent”有许多“ModelChild”,下面是我的模型结构:

class ModelParent(models.Model):
    ... some params ...


class ModelChild(models.Model):
    TYPES = (
        (1, 'First'),
        (2, 'Second'),
    )
    parent = models.ForeignKey(ModelParent, on_delete=models.CASCADE, related_name='childs')
    type = models.SmallIntegerField(choices=TYPES, default=0)

当前,数据库中只有一个“ModelChild”属于数据库中当前唯一的“ModelParent”,“ModelChild”的“type”值等于“1”,我正在获取“ModelParent”对象,我需要将其“childs”(类型为“1”)的计数以及“childs”(类型为“2”)的计数聚合到该对象中,我就是这样做的:

^{pr2}$

查询不会引发任何错误,但在查看响应时,两个批注的值都为“1”,而对于“第一个”批注,它的值应为“1”,而对于“第二个”批注,则应为“0”。在

我还注意到,无论我在过滤器“filter=Q(childs_uutype=1)”中设置什么值为“childs_utype”,结果总是一样的,我可以这样设置,例如:“childs_utype=10”,计数仍然等于“1”。。就像整个'filter'参数被忽略一样。在


Tags: 对象模型数据库类型modelmodelstypefilter
1条回答
网友
1楼 · 发布于 2024-09-27 19:27:02

基于this answer我设法用这种方式实现了它,但我需要在子查询中添加“output_field”和注释的“Coalesce”,“output_field”是django所必需的,没有它它它就无法工作,并且需要“Coalesce”,因为如果结果为零,默认情况下子查询将返回“null”,因此“Coalesce”的作用是在结果为null时检索一个默认值,在本例中我将其设置为零:

    childs_base_query = ModelChild.objects.filter(parent=OuterRef('pk'))
    first_type_query = Subquery(childs_base_query
                           .filter(type=1)
                           .values('parent')
                           .annotate(count=Count('pk'))
                           .values('count')
                           , output_field=IntegerField())

    second_type_query = Subquery(childs_base_query
                              .filter(type=2)
                              .values('parent')
                              .annotate(count=Count('pk'))
                              .values('count')
                              , output_field=IntegerField())

    queryset = ModelParent.objects \
        .annotate(first_count=Coalesce(first_type_query, 0)) \
        .annotate(second_count=Coalesce(second_type_query, 0))

我希望它能帮助别人。在

相关问题 更多 >

    热门问题