I'm currently placing the result of a QuerySet into a JSON string to be used by my js frontend.
Currently this is easy enough using .values() and simplejson:
simplejson.dumps(list(Task.objects.filter(list=mylist).values()))
I've now added a ManyToMany field in my Task object, would like to have it included in my output without having each Task object repeated for every value of the ManyToMany relationship.
If I just did Task.objects.filter(list=mylist).values('myManyToManyField', 'someOtherField')
The output would have a separate object/row for each value of myManyToManyField
[{'myManyToManyField': 1, 'someOtherField': 'valueOne'},
{'myManyToManyField': 2, 'someOtherField': 'valueOne'},
{'myManyToManyField': 1, 'someOtherField': 'valueTwo'}]
Is there any way to get this result instead?:
[{'myManyToManyField': [1,2], 'someOtherField': 'valueOne'},
{'myManyToManyField': 1, 'someOtherField': 'valueTwo'}]
The only solution I have right now is to loop over all the Task
objects and build the output manually, placing the ManyToMany value within it as desired. Is there a better way to do this? If not - would this be horribly inefficient?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With