JsonResponse with model instance including M2M

125 views Asked by At

It seems that you cannot replace

from django.core import serializers
from django.http import HttpResponse, JsonResponse

qs = MyModel.objects.filter(pk=1)
data = serializers.serialize('json', qs, fields=('id', 'name', 'my_m2m_field'))
# I want data of the one instance only.
data = data[data.find('{', 3, 15):data.rfind('}', -60, -3) + 1]
return HttpResponse(data, content_type='application/json')

by JsonResponse, can you? (I don't mean to replace just the last line by return JsonResponse(data) for this doesn't make sense in my opinion.)

For this results in an error:

my_m2m_ids = qs[0].my_m2m_field.all().values_list('id', 'flat=True') # = [3, 2]
dic = {'my_m2m_ids': my_m2m_ids} # also tried `my_m2m_ids[:]`
dic.update(qs.values('id', 'name')[0]) # also tried `list(qs.`… and `dict(qs.`…
return JsonResponse(dic) # also tried `safe=False`

Error: TypeError at <path> [3, 2] is not JSON serializable. I don't know exactly why but I think it's caused somehow by the ValuesQuerySet retruned by values() or by the ValuesListQuerySet returnd by values_list().

Is there any better/shorter solution? For I think it's both not ideal.

Update

It works after converting the ValuesListQuerySet to a list (by my_m2m_ids = list(my_m2m_ids), but my_m2m_ids[:] obviously doesn't work).

But I still loved to be able to use JsonResponse like this: return JsonResponse(MyModel.objects.get(pk=1).only('id', 'name', 'my_m2m_field)) (or similar).

0

There are 0 answers