Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output of values() on a QuerySet with ManyToMany fields

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?

like image 935
xqwzts Avatar asked Aug 20 '12 02:08

xqwzts


1 Answers

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

like image 132
opportunity356 Avatar answered Mar 15 '23 00:03

opportunity356