9
9
95506682021-03-10 13:52:41
Django
9550668, 2021-03-10 13:52:41

Why does the serializer work differently?

Hello everybody!

I have several serializers:
User_avatar_serializer.py:

from rest_framework import serializers

from users.models import UserAvatar:
class UserAvatarSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserAvatar
        fields = [
            "local_url",
        ]

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        return ret["local_url"]


User_serializer.py:
from rest_framework import serializers

from api.users.serializers.user_avatar_serializer import UserAvatarSerializer
from users.models import User


class UserShortSerializer(serializers.ModelSerializer):
    avatar = UserAvatarSerializer(required=False, read_only=True)

    class Meta:
        model = User
        fields = [
            "id",
            "username",
            "first_name",
            "last_name",
            "avatar",
            "first_time",
        ]


If I access the UserShortSerializer serializer through a view, then the issuance of a link to the avatar through the internal call to UserAvatarSerializer is as follows:
...
"avatar": " 127.0.0.1:8000/media/user/avatar/1bbcd0e1-b7a8-44f... ",
...


If I access other serializers that are not related to users and I need to return information on the requested user in the response, then I rewrite the to_representation function, using the example:
def to_representation(self, instance):
        ...   
        ret["participants_info"] = {
            ...
            "avatars": UserAvatarSerializer(instance=avatar_list, many=True, required=False).data,
            ...
        }
        return ret


In this case, I get the output:
...
"avatars": [
"/media/home/app/marathon/static/images/bg01.jpg"
],
...

I don't understand why " 127.0.0.1:8000 " is missing in the second output?
It is clear that in the first option I redirect the avatar field to the UserAvatarSerialize serializer:
avatar = UserAvatarSerializer(required=False, read_only=True)

And in the second I call the serializer like this:
UserAvatarSerializer(instance=avatar_list, many=True, required=False).data,


How can I finally make it so that in both cases the domain name is written first?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
django-developer, 2021-03-11
@9550668

I did not specify the context in which the request should be forwarded.
More details in the documentation: https://www.django-rest-framework.org/api-guide/se...

A
Alexander Taratin, 2018-01-05
@Taraflex

Use CouchDB on the server
. On the PouchDB client, there are implementations for Browsers, Android, IOS (if you wish, you can probably screw it under the desktop)
https://pouchdb.com/faq.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question