gpt4 book ai didi

python - Django 查询集注释字段为列表/查询集

转载 作者:太空狗 更新时间:2023-10-29 20:10:24 25 4
gpt4 key购买 nike

我正在尝试使用 Django 注释来创建查询集字段,它是一些相关模型属性的值列表。

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。我知道这个语法是错误的。感谢您的帮助。

最佳答案

如果您正在使用 postgresqldjango >= 1.9,您可以使用 postgres 特定的聚合函数,例如 ArrayAgg :

Returns a list of values, including nulls, concatenated into an array.

如果您需要使用分隔符连接这些值,您也可以使用 StringAgg .

关于python - Django 查询集注释字段为列表/查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43203014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com