django serialize foreign key objects

后端 未结 2 1188
后悔当初
后悔当初 2020-12-18 07:06
  • Serialize django model with foreign key models
  • Serializing Foreign Key objects in Django
  • get foreign key objects in a single query - Django
相关标签:
2条回答
  • 2020-12-18 07:12

    You could use Django REST frameworks' serializers.

    0 讨论(0)
  • 2020-12-18 07:17

    One potential way around this is to construct your own dictionary object based on the returns of a queryset. You'd 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 to work.

    import json
    
    0 讨论(0)
提交回复
热议问题