调用特定URL时,不要在Django REST框架中给予完整的媒体URL

hrysbysz  于 2023-07-01  发布在  Go
关注(0)|答案(1)|浏览(102)

在将图像更改为URL后,我将其提供给API。然而,即使序列化已经通过相同的序列化器进行,当请求被发送到特定的url时,它是以media/image_name而不是www.example.com的形式传输127.0.0.1:8000/media/image_name。你能帮我通过查看我的代码找到原因吗?
views.py

class ReadAllListPostView (ModelViewSet) :
    serializer_class = PostSerializer
    queryset = Post.objects.all().order_by('-pk')
    pagination_class = LargeResultsSetPagination

class ReadCommentView (ModelViewSet) :
    serializer_class = CommentSerializer
    queryset = Comment.objects.all().order_by('pk')

    def list (self, request, *args, **kwargs) :
        postId = self.kwargs.get('post_id')
        post = Post.objects.get(pk=postId)
        post.view_count = post.view_count + 1
        post.save(update_fields=('view_count', ))

        comments = self.queryset.filter(post=postId)
        serializer = self.serializer_class(comments, many=True)
        
        return Response(serializer.data)

feed\serializers.py

class PostSerializer (serializers.ModelSerializer) :
    owner = userProfileSerializer(read_only=True)
    like_count = serializers.ReadOnlyField()
    comment_count = serializers.ReadOnlyField()
    images = ImageSerializer(read_only=True, many=True)
    liked_people = LikeSerializer(many=True, read_only=True)
    tag = serializers.ListField(child=serializers.CharField(), allow_null=True, required=False)
    comments = CommentSerializer(many=True, read_only=True)

    class Meta :
        model = Post
        fields = ('id', 'owner', 'title', 'content', 'view_count', 'images', 'like_count', 'comment_count', 'liked_people', 'tag', 'created_at', 'comments')

    def create (self, validated_data) :
        images_data = self.context['request'].FILES
        post = Post.objects.create(**validated_data, created_at=str(datetime.now().astimezone().replace(microsecond=0).isoformat()))
        
        for i in range(1, 6) :
            image_data = images_data.get(F'image{i}')

            if image_data is None :
                break

            Image.objects.create(post=post, image=image_data)

        return post

    def to_representation (self, instance) :
        data = super().to_representation(instance)

        images = data.pop('images')
        liked_people = data.pop('liked_people')
        comments = data.pop('comments')

        images_array = [image.get('image') for image in images]
        liked_people_array = [liked_person.get('liked_people') for liked_person in liked_people]
        comments_array = [comment for comment in comments]

        if comments_array != [] :
            if len(comments_array) == 1 or len(comments_array) == 2:
                data.update({'image_urls': images_array, 'liked_people': liked_people_array, 'comment_preview': comments_array})

            else :
                comments_preview_array = []

                for i in range(2) :
                    random_comment = random.choice(comments_array)
                    comments_array.remove(random_comment)
                    comments_preview_array.append(random_comment)

                data.update({'image_urls': images_array, 'liked_people': liked_people_array, 'comment_preview': comments_preview_array})
                    
        else :
            data.update({'image_urls': images_array, 'liked_people': liked_people_array})

        return data

API\serializers.py

class userProfileSerializer (serializers.ModelSerializer) :
    image = serializers.ImageField(use_url=True)
    following = serializers.SerializerMethodField()
    followers = serializers.SerializerMethodField()
    
    class Meta :
        model = User
        fields = ['id', 'email', 'username', 'image', 'following', 'followers']

    def get_following (self, obj) :
        serializer = FollowingSerializer(obj.following.all(), many=True).data
        return len(serializer)

    def get_followers (self, obj) :
        serializer = FollowersSerializer(obj.followers.all(), many=True).data
        return len(serializer)

如果我让你看第1篇文章的评论(feed/post/1/comments)

[
    {
        "comment_id": 1,
        "owner": {
            "id": 2,
            "email": "dsgsdg",
            "username": "sdgdsg",
            "image": "/media/1-2_%EA%B2%8C%EC%8B%9C%EB%AC%BC.jpg",
            "following": 0,
            "followers": 0
        },
        "content": "nice to meet you",
        "created_at": "2020-10-19T20:35:39+09:00"
    },
    {
        "comment_id": 2,
        "owner": {
            "id": 2,
            "email": "dsgdsf",
            "username": "dsgdsgf",
            "image": "/media/1-2_%EA%B2%8C%EC%8B%9C%EB%AC%BC.jpg",
            "following": 0,
            "followers": 0
        },
        "content": "nice to meet yall",
        "created_at": "2020-10-19T20:48:51+09:00"
    },
    {
        "comment_id": 3,
        "owner": {
            "id": 2,
            "email": "dsgdsg",
            "username": "dsgsdg",
            "image": "/media/1-2_%EA%B2%8C%EC%8B%9C%EB%AC%BC.jpg",
            "following": 0,
            "followers": 0
        },
        "content": "gang gnagn",
        "created_at": "2020-10-19T20:49:06+09:00"
    },
    {
        "comment_id": 4,
        "owner": {
            "id": 2,
            "email": "sdgsdfg",
            "username": "dsgsd",
            "image": "/media/1-2_%EA%B2%8C%EC%8B%9C%EB%AC%BC.jpg",
            "following": 0,
            "followers": 0
        },
        "content": "yrdy",
        "created_at": "2020-10-19T20:54:21+09:00"
    }
]

如果图片的基本URL被截断如下,但整个帖子被请求(feed/post/all)

[
    {
        "id": 3,
        "owner": {
            "id": 2,
            "email": "safa",
            "username": "safasd",
            "image": "http://127.0.0.1:8000/media/1-2_%EA%B2%8C%EC%8B%9C%EB%AC%BC.jpg",
            "following": 0,
            "followers": 0
        },
        "title": "hi",
        "content": "sadfsad",
        "view_count": 1,
        "like_count": 1,
        "comment_count": 0,
        "tag": null,
        "created_at": "2020-10-21T21:55:29+09:00",
        "image_urls": [],
        "liked_people": [
            2
        ]
    },
    {
        "id": 2,
        "owner": {
            "id": 2,
            "email": "sadfa",
            "username": "asdfa",
            "image": "http://127.0.0.1:8000/media/1-2_%EA%B2%8C%EC%8B%9C%EB%AC%BC.jpg",
            "following": 0,
            "followers": 0
        },
        "title": "hi",
        "content": "sdafadf",
        "view_count": 1,
        "like_count": 1,
        "comment_count": 0,
        "tag": null,
        "created_at": "2020-10-20T20:45:50+09:00",
        "image_urls": [],
        "liked_people": [
            2
        ]
    },
    {
        "id": 1,
        "owner": {
            "id": 2,
            "email": "sadfas",
            "username": "sadfasdf",
            "image": "http://127.0.0.1:8000/media/1-2_%EA%B2%8C%EC%8B%9C%EB%AC%BC.jpg",
            "following": 0,
            "followers": 0
        },
        "title": "hello",
        "content": "nice to meet you",
        "view_count": 16,
        "like_count": 2,
        "comment_count": 4,
        "tag": [
            "안녕 쟈기"
        ],
        "created_at": "2020-10-19T20:20:17+09:00",
        "image_urls": [],
        "liked_people": [
            2,
            1
        ],
        "comment_preview": [
            {
                "comment_id": 2,
                "owner": {
                    "id": 2,
                    "email": "safasd",
                    "username": "safasfd",
                    "image": "http://127.0.0.1:8000/media/1-2_%EA%B2%8C%EC%8B%9C%EB%AC%BC.jpg",
                    "following": 0,
                    "followers": 0
                },
                "content": "nice to meet yall",
                "created_at": "2020-10-19T20:48:51+09:00"
            },
            {
                "comment_id": 4,
                "owner": {
                    "id": 2,
                    "email": "safad",
                    "username": "sadfas",
                    "image": "http://127.0.0.1:8000/media/1-2_%EA%B2%8C%EC%8B%9C%EB%AC%BC.jpg",
                    "following": 0,
                    "followers": 0
                },
                "content": "safasd",
                "created_at": "2020-10-19T20:54:21+09:00"
            }
        ]

这样,媒体URL就满了。

smdncfj3

smdncfj31#

发生此行为是因为序列化程序在某些情况下获取上下文,而在其他情况下则不获取上下文。
当序列化器在上下文中获得请求时,它试图构建到媒体http://...的绝对URL。当它没有在上下文中获取请求时,它只会构建相对url /media/
您有两个选择:
1.为所有序列化器提供上下文中的请求。
1.从一些序列中删除请求上下文。
要删除传递给ViewSets中序列化器的上下文,您可以重新声明get_serializer_context方法:

def get_serializer_context(self):
        return {}

相关问题