django serialize foreign key objects

后端 未结 2 1186
后悔当初
后悔当初 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: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
    

提交回复
热议问题