Skip to content

How to serialize foreign keys in the returned content? #453

Answered by wu-clan
wu-clan asked this question in Q&A
Discussion options

You must be logged in to vote

As I described, it forced the use of response=List[Schema], but he has only bare data

If I want to put the data in schema model, like:

class Response(Schema)
    code: 200
    msg: str = 'Success'
    data: Any = None

like demo, i need to do this

@api.get("/tasks")
def tasks(request):
    queryset = Task.objects.select_related("owner")
    return Response(data=serialize('json', queryset))

return will be like:

{
  "code": 200,
  "msg": "Success"
  "data": [
      {
          "id": 1, 
          "title": "Task 1",
          "is_completed": false,
          "owner": 1  # < --- !!! not resolve
      },
      {
          "id": 2, 
          "title": "Task 2",
          "is_completed": false,
 …

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@SmileyChris
Comment options

@wu-clan
Comment options

Answer selected by wu-clan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants