Django serializes foreign key objects

There are a couple of questions that ask the same thing. But they are from 2010, and it did not help me. So, I believe that since 2010 it is possible to upgrade to this?

In google, I found a link that explains the use of natural keys . However, my problem is getting foreign objects from django.contrib.auth.models.User, so this does not help.

My problem is the following. I want to serialize a QuerySet to get foreign key objects, because I want to pass it as JSON to the client. The serializer django.coredoes not do this. Therefore, in my case, for a simple problem, I added another field to the model to contain the value that I need from a foreign object. But he, however, introduces redundant data.

In my sample model, it contains username, which I would like to delete, if possible, and instead get it using a foreign key.

    user = models.ForeignKey(User)
    username = models.CharField(max_length=100, null=False)
+5
source share
2 answers

One possible way is to build your own dictionary object based on the query results. You would do something like this:

queryset = Model.objects.all()
list = [] #create list
for row in queryset: #populate list
    list.append({'title':row.title, 'body': row.body, 'name': row.user.username})
recipe_list_json = json.dumps(list) #dump list as JSON
return HttpResponse(recipe_list_json, 'application/javascript')

You need to import json for this.

import json
+6

Django REST serializers.

+1

All Articles