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'))
)
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.
I have done something like that:
Now there are lists of
None
orpk
under eachfield_a
,field_b
andfield_c
for every object in queryset. You can also define other default value forCase
instead ofNone
.If you are using
postgresql
anddjango >= 1.9
, you could use postgres specific aggregating functions e.g.ArrayAgg
:In case, you need to concatenate these values using a delimiter, you could also use
StringAgg
.