Desiigner
Desiigner

Reputation: 2336

Access a single serializer (Django Rest Framework)

I might not get understand the concept of serializers right but as I think, serializers are used to represent python objects as json objects.

So my question is, I've got a model:

class User(AbstractUser):
    messages = models.IntegerField(default=0)
    signup_date = models.DateField(auto_now_add=True)
    last_msg = models.DateField(null=True, blank=True)

and a serializer:

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ['username', 'password', 'email']

As my API View returns json, I want to pass a serialized username but I don't know how to achieve it.

This is a piece of code written without serializers so I'm trying to get the same result using them:

chat_session = ChatSession.objects.get(uri=uri)
    owner = chat_session.owner

    if owner != user:  # Only allow non owners join the room
        chat_session.members.get_or_create(
            user=user, chat_session=chat_session
        )

    owner = deserialize_user(owner)
    members = [
        deserialize_user(chat_session.user)
        for chat_session in chat_session.members.all()
    ]

How can I access my Serializer for a specific user instead of using a custom deserialize_user function

Upvotes: 0

Views: 28

Answers (1)

AKX
AKX

Reputation: 169268

I believe

members = UserSerializer(many=True).to_representation(chat_session.members.all())

would do the trick.

Upvotes: 1

Related Questions