Django queryset注释字段为列表/查询集 [英] Django queryset annotate field to be a list/queryset
问题描述
我正在尝试使用django注释创建queryset字段,该字段是一些相关模型属性的值的列表。
I'm trying to use django annotation to create queryset field which is a list of values of some related model attribute.
queryset = ...
qs = queryset.annotate(
list_field=SomeAggregateFunction(
Case(When(related_model__field="abc"), then="related_model__id")
),
list_elements=Count(F('list_field'))
)
我正在考虑使用分隔符将所有这些ID串联起来,但是我不知道合适的功能。另一种解决方案是将list_field设置为 queryset
。我知道这种语法是错误的。谢谢您的帮助。
I was thinking about about concatenating all these id with some separator, but i don't know the appropriate functions. Another solution is to make list_field a queryset
. I know this syntax is wrong. Thank you for any help.
推荐答案
如果您使用的是 postgresql
和 django> = 1.9
,您可以使用postgres特定的聚合函数,例如
ArrayAgg
:
If you are using postgresql
and django >= 1.9
, you could use postgres specific aggregating functions e.g.
ArrayAgg
:
返回值列表,包括连接到数组的空值。
Returns a list of values, including nulls, concatenated into an array.
如果需要使用定界符将这些值连接起来,还可以使用 StringAgg
。
In case, you need to concatenate these values using a delimiter, you could also use StringAgg
.
这篇关于Django queryset注释字段为列表/查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!