question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Using SerializerMutation with Relay

See original GitHub issue

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.

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:7
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
dan-klassoncommented, Aug 6, 2019

@jkimbo

Before creating a PR for this I wanted to make it support m2m fields as well. But I ran into some issues.

This is the code I came up with.

            model_field = model._meta.get_field(field)

            # convert relay ID to PK
            if isinstance(model_field, (AutoField, ForeignKey)):
                _, input[field] = from_global_id(value)
            elif isinstance(model_field, ManyToManyField):
                values = ast.literal_eval(value)
                input[field] = [from_global_id(val)[1] for val in values]

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

When passing in the ids as a list. The value of value is not deserialized and is not valid JSON. Hence the use of ast.literal_eval. Other than that workaround, it also returns this:

'memberLevels': '<QuerySet [<MemberLevel: level 2>]>'

2reactions
stale[bot]commented, May 16, 2020

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Graphene Django mutation returning object with subobjects fails
When I execute a mutation (with SerializerMutation) and return the created object, the response contains an AssertionError that states
Read more >
GraphQL Simplistic CRUD - Sarit Ritwirune - Medium
I know they are 3 approaches that GraphQL can do with mutations(ModelForm, ModelSerializer, and Relay). And to delete the instance you have to...
Read more >
Mutations - Graphene-Python
Relay ¶. You can use relay with mutations. A Relay mutation must inherit from ClientIDMutation and implement the mutate_and_get_payload method:.
Read more >
Integration with Django Rest Framework - Graphene-Python
You can create a Mutation based on a serializer by using the SerializerMutation base class: from graphene_django.rest_framework.mutation import ...
Read more >
Chapter 4. Graphene - Michael Stromer
For each DjangoObjectType , we add a unique node. With Django and Graphene, we are also utilizing cursor-based pagination, provided by Relay. For...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found