2

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"},
                                                    ...
]
Community
  • 1
  • 1
carlosedb
  • 21
  • 4
  • Serching for the solution I found something useful to those (like me) are dealing with UTF8 data in the django [documentation](https://docs.djangoproject.com/en/1.3/topics/serialization/#id2) – carlosedb Apr 11 '13 at 12:47
  • http://stackoverflow.com/questions/3753359/serializing-foreign-key-objects-in-django – dm03514 Apr 11 '13 at 13:53
  • some trouble with utf-8 can be soved looking http://code.google.com/p/wadofstuff/issues/detail?id=19 – carlosedb Apr 11 '13 at 19:08
  • Possible duplicate of [Adding duplicate keys to JSON with python](http://stackoverflow.com/questions/29519858/adding-duplicate-keys-to-json-with-python) – Paul Sweatte Oct 21 '15 at 12:46

0 Answers0