在django中使用groupconcat和其他注解

uurity8g  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(489)

我使用了一个注解,它在返回文章列表时统计得票/反对票:

  1. queryset = queryset.annotate(
  2. upvotes_count=models.Sum(
  3. models.Case(
  4. models.When(likes__like_state=1, then=1),
  5. default=0,
  6. output_field=models.IntegerField()
  7. )
  8. )
  9. ).annotate(
  10. downvotes_count=models.Sum(
  11. models.Case(
  12. models.When(likes__like_state=-1, then=1),
  13. default=0,
  14. output_field=models.IntegerField()
  15. ))
  16. )

但是每篇文章也有一些类别,比如许多相关字段,我需要返回那些以逗号分隔的类别,所以我编写了这个函数:

  1. class GroupConcat(models.Aggregate):
  2. function = 'GROUP_CONCAT'
  3. template = "%(function)s(%(distinct)s %(expressions)s %(separator)s)"
  4. def __init__(self, expression, distinct=False, separator=', ',**extra):
  5. super(GroupConcat, self).__init__(
  6. expression,
  7. distinct='DISTINCT' if distinct else '',
  8. separator="SEPARATOR '%s'" % separator,
  9. output_field=models.CharField(),
  10. **extra
  11. )

并将其添加到我的注解中:

  1. queryset = queryset.annotate(category=GroupConcat('categories__name'))

很好,但是 upvotes_count 以及 downvotes_count 变得疯狂并开始繁殖(!)按类别数量列出的结果。
所以问题是:“有没有一种方法可以在django中使用groupconcat而不分解sum注解?”

suzh9iv8

suzh9iv81#

很好的解决方案。但要使用groupbyfield进行操作,应该使用orderbystatement。例如:
store.objects.all().values('value').order_by('value').annotate(stores=groupconcat('id'))
将生成sql语句
选择 store . value ,组\u concat( store . id 分隔符“,”)为 storesstore 哪里 store . value >0分组依据 store . value 订货人 store . value asc公司
结果是值,存储1“16,27”
如果没有命令,它会是这样的:
选择 store . value ,组\u concat( store . id 分隔符“,”)为 storesstore 哪里 store . value >0分组依据 store . id 订货人 store . value asc公司
结果就是价值,存储1 16 2 27

相关问题