Django Serialize Queryset to JSON to construct RESTful response with only field information and id

前端 未结 1 824
不思量自难忘°
不思量自难忘° 2021-02-04 04:00

I currently have a Post model with \'title\' and \'summary\' fields. I\'m retrieving all the Posts and returning them as JSON as part of a RESTful API interface.

Here\'

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 05:00

    What you want to achieve is subset of fields dumped to json.

    What you're doing is serializing whole django's ORM objects. Not good.

    Keep it simple:

    import json
    
    posts = (Post.objects.filter(owner=authenticated_user)
                         .values('id', 'title', 'summary'))
    json_posts = json.dumps(list(posts))
    

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