Skip to content

SerializerMethodField method does not get called #760

Closed
@B4rtware

Description

@B4rtware

I am trying to understand how I would implement an additional field (token) inside the serializer class from rest_framework. This code snippet works in native django rest framework but unfortunately not in conjunction with graphene_django.

Using this serializer:

from rest_framework import serializers
from graphql_jwt.utils import jwt_payload, jwt_encode
from django.contrib.auth.models import User


class UserSerializer(serializers.ModelSerializer):
    # sending back token for initial login
    token = serializers.SerializerMethodField()

    def get_token(self, obj):
        # generate new token
        return jwt_encode(jwt_payload(obj))
        
    class Meta:
        model = User
        fields = ["password", "username", "email", "token"]

with this graphql mutation:

mutation {
  createUser(input: {username: "john_doe", password: "f", email: "john_doe@f.com"}) {
    errors {
      messages
    },
    username,
    token
  }
}

it returns the response:

{
  "data": {
    "createUser": {
      "errors": null,
      "username": "john_doe",
      "token": "john_doe"
    }
  }
}

Here you can see that the token will be filled with the used username instead of a generated token.

I really want to use those Serializer classes because of the validation function. I have already read about some limitations e.g "extra_kwargs" but did not found something specific about SerializerMethodField class. I have already thought about a workaround by initializing the Serializer class inside of a class UserMutation(graphene.Mutation) and calling its method is_valid but I hope for an explanation what I am doing wrong to use the documented procedure.


I would expect:

{
  "data": {
    "createUser": {
      "errors": null,
      "username": "john_doe",
      "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFstZSI6InlkbGFkbWluIiwiZXhwIjoxNTY3NDMwMdzk3LCJvcmlnSWFs0IjoxNTY3NDMwMDk3fQ.zt-XQN5k8zWrAMpNWN-xt_vRe6topM7kzFVSm6CT0Vs"
    }
  }
}

  • CPython 3.7.4 64bit
  • Windows 10

  • django 2.2.4
  • graphene-django 2.5.0
  • djangorestframework 3.10.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions