[Django]-Output of values() on a QuerySet with ManyToMany fields

20👍

from django.contrib.postgres.aggregates import ArrayAgg

Task.objects.filter(list=mylist).annotate(arr_field=ArrayAgg('myManyToManyField')).values('arr_field', 'someOtherField')

Output:

[{'arr_field': [1,2], 'someOtherField': 'valueOne'},
 {'arr_field': 1, 'someOtherField': 'valueTwo'}]

3👍

It seems that there is no other way but iterate over all Task objects.

Django’s documentation warns about using ‘values()’ on ‘ManyToManyField’.

It would not be

horribly inefficient

if you do this way All the values of the many to many field : Django

3👍

You can use Django’s serializers:

import json
from django.core import serializers

json_data = serializers.serialize("json", Task.objects.all())

If you want to extract the fields only, do the following:

data = [i['fields'] for i in json.loads(json_data)]

Leave a comment