Aurora
Aurora

Reputation: 133

Django model serialization returns only primary key for foreign key

i am building blog site with Django. After serialization, the Post model which has a foreign key field of Django built-in User model, Post models are returned with the integer foreign key reference to the User model while i am expecting the whole User object data rather only getting the integer number. the Post models.py:

from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
    author = models.ForeignKey(User,on_delete=models.CASCADE)
    body = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

the serializers.py:

from rest_framework  import serializers
from .models import Post
class PostSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ('id', 'author','body','created_at')
        model = Post

the views.py:

from django.shortcuts import render
from rest_framework import generics
from .models import Post
from .serializers import PostSerializer
from .permissions import IsAuthorOrReadOnly

class PostList(generics.ListCreateAPIView):
    serializer_class = PostSerializer
    queryset = Post.objects.all().order_by('-created_at')#sorted by created_at descending 

class PostDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (IsAuthorOrReadOnly,)
    serializer_class = PostSerializer
    queryset = Post.objects.all()

i want

 {
        "id": 15,
        "author": {"fisrt_name":"firstname","last_name":"namelast","username":"username1","email":"[email protected]"},
        "body": "hello world2",
        "created_at": "2020-12-23T13:53:17.741635Z"
    }

instead of

 {
        "id": 15,
        "author": 21,
        "body": "hello world2",
        "created_at": "2020-12-23T13:53:17.741635Z"
    }

Upvotes: 3

Views: 1289

Answers (1)

babak gholamirad
babak gholamirad

Reputation: 568

you can make your User Serializer like this:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = [...] # put your fields instead of "..."
        depth = 1

and then use nested serializer like this :

class PostSerializer(serializers.ModelSerializer):
    author = UserSerializer(many=false)
    class Meta:
        fields = ('id','body','created_at')
        model = Post

Upvotes: 3

Related Questions