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
- [Django]-Django: permission denied when trying to access database after restore (migration)
- [Django]-Django debug display all variables of a page
- [Django]-Django: show/log ORM sql calls from python shell
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)]
- [Django]-How to manage local vs production settings in Django?
- [Django]-Filtering ListAPIView in django-rest-framework
- [Django]-How to loop through httprequest post variables in python
Source:stackexchange.com