简体   繁体   中英

How to serialize object field in django rest framework

I have Profile model, which is auth model. And I have Blog model. I want to serialize model as it will give me {author: {user_name:.., photo: photo_path}, blog_title:some_title, ..} . Shortly, I want use author field as inner serialiser. I have already ProfileSerialiser and BlogSerializer. Here's my BlogList serializer:

class BlogListSerializer(serializers.ModelSerializer):
    author = MiniProfileSerializer()
    class Meta:
        model = Blog
        fields = ['title', 'content', 'like_count', 'author']
        read_only_fields = ['views', 'author', 'like_count']

And MiniProfileSerializer:

class MiniProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = Profile
        fields = ['user_name', 'image']

and view:

class BlogListAPIView(generics.ListCreateAPIView):
    serializer_class = BlogListSerializer
    queryset = Blog.published.all()
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

Django REST Framework does not support writing to a nested serializer out of the box. You can check out DRF Writeable Nested , or write your own custom behavior on create by overwriting create() in the BlogListSerializer .

EDIT : Here's some more docs on the topic: https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM