I have a model with ManyToManyField to another model. I would like to get all the info on a particular record (including the related info from other models) return by JSON.
Before posting my question I've read this but its not the same I'm looking for. I'm not using piston.
models.py
class Subject(models.Model):
description = models.CharField(max_length=200)
def __unicode__(self):
return self.description
class Practice(models.Model):
title = models.CharField(max_length=200)
main_subject = models.ForeignKey(to=Subject)
related_subjects = models.ManyToManyField(to=Subject, related_name="practices")
def __unicode__(self):
return "%s" % (self.title)
I implemented a generic list view that returns a list of Practice instances in json format ...
listviews.py
class PracticeListView(ListView):
def get_queryset(self):
return Practice.objects.all()
class PracticeListViewJSON(PracticeListView):
def get(self, request, *args, **kwargs):
queryset = self.get_queryset()
json_serializer = serializers.get_serializer("json")()
data = json_serializer.serialize(queryset, ensure_ascii=False)
return HttpResponse(data, content_type="application/json")
But the json data doesn't brings the Subject description values, but just its references as ids.
json
[{"pk": 1, "model": "app.pratice", "fields": {"related_subjects": [2, 4]}}]
What should I do to have a return like this
[{"pk": 1, "model": "app.pratice",
"fields": {"related_subjects": ["model": "app.subject",
"fields": {"description": "description of the subject #1"},
"model": "app.subject",
"fields": {"description": "description of the subject #2"},
...
]