【发布时间】:2018-10-07 00:43:28
【问题描述】:
我在返回文章列表时使用了计算赞成/反对票的注释:
queryset = queryset.annotate(
upvotes_count=models.Sum(
models.Case(
models.When(likes__like_state=1, then=1),
default=0,
output_field=models.IntegerField()
)
)
).annotate(
downvotes_count=models.Sum(
models.Case(
models.When(likes__like_state=-1, then=1),
default=0,
output_field=models.IntegerField()
))
)
但是每篇文章也有一些类别作为ManyToMany相关字段,我需要以逗号分隔返回这些类别,所以我写了这个函数:
class GroupConcat(models.Aggregate):
function = 'GROUP_CONCAT'
template = "%(function)s(%(distinct)s %(expressions)s %(separator)s)"
def __init__(self, expression, distinct=False, separator=', ', **extra):
super(GroupConcat, self).__init__(
expression,
distinct='DISTINCT' if distinct else '',
separator="SEPARATOR '%s'" % separator,
output_field=models.CharField(),
**extra
)
并将其添加到我的注释中:
queryset = queryset.annotate(category=GroupConcat('categories__name'))
它工作正常,但 upvotes_count 和 downvotes_count 发疯了,开始将结果乘以(!)类别数量。
所以问题是:“有没有办法在 Django 中使用 GROUP_CONCAT 而不分解 SUM 注释?”
【问题讨论】:
标签: mysql django django-orm