Skip to content

Using SerializerMutation with Relay #728

Open
@dan-klasson

Description

@dan-klasson

I'm overriding mutate_and_get_payload to convert the global ID to PK:

class BaseSerializerMutation(SerializerMutation):

    class Meta:
        abstract = True

    @classmethod
    def mutate_and_get_payload(cls, root, info, **input):

        model = cls._meta.serializer_class.Meta.model

        for field, value in input.items():

            if not hasattr(model, field):
                continue

            model_field = model._meta.get_field(field)

            # convert relay ID to PK
            if isinstance(model_field, (AutoField, ForeignKey)):
                _, input[field] = from_global_id(value)

        return super().mutate_and_get_payload(root, info, **input)

Then I also need to tell DRF that the global ID is not an integer:

from rest_framework import serializers


class BaseModelSerializer(serializers.ModelSerializer):
    id = serializers.CharField(required=False)

Ideally this should already be supported by graphene-django. Perhaps have a RelaySerializerMutation and a RelayModelSerializer? I can create a PR if you're OK with adding this.

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