简体   繁体   English

如何在django rest框架中序列化object字段

[英]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, ..} .我有配置文件 model,它是 auth model。我有博客 model。我想序列化 model,因为它会给我{author: {user_name:.., photo: photo_path}, blog_title:some_title, ..} Shortly, I want use author field as inner serialiser.不久,我想使用 author 字段作为内部序列化程序。 I have already ProfileSerialiser and BlogSerializer.我已经有 ProfileSerialiser 和 BlogSerializer。 Here's my BlogList serializer:这是我的 BlogList 序列化程序:

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:和 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. Django REST 框架不支持立即写入嵌套序列化程序。 You can check out DRF Writeable Nested , or write your own custom behavior on create by overwriting create() in the BlogListSerializer .您可以查看DRF Writeable Nested ,或者通过覆盖BlogListSerializer中的create()来编写您自己的自定义行为。

EDIT : Here's some more docs on the topic: https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers编辑:这是关于该主题的更多文档: https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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