Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BaseDjangoFormMutation should use from_global_id when fetching existing instance #460

Closed
nuarhu opened this issue Jun 28, 2018 · 7 comments
Labels

Comments

@nuarhu
Copy link

nuarhu commented Jun 28, 2018

We are using DjangoFormMutations (#217), and what I'm not sure about is how Django's ID/PKs are resolved in the process. They still appear in base64 encoding in the GraphQL output but in BaseDjangoFormMutation method they are processed as is.

The error returned from GraphQL shows that the instance is fetched using the string with the base64 encoded ID instead of the decoded PK integer value.

"errors": [
  {
    "message": "invalid literal for int() with base 10: 'UHJvamVjdE5vZGU6MTA1'",

I think the following code from /graphene_django/forms/mutation.py should use from_global_id instead of the value as is:

@classmethod
def get_form_kwargs(cls, root, info, **input):
    kwargs = {'data': input}

    pk = input.pop('id', None)
    if pk:
        instance = cls._meta.model._default_manager.get(pk=pk)
        kwargs['instance'] = instance

    return kwargs

I'm not 100% sure about this. We are using UUIDs next to Django's IDs so I had to extend get_form_kwargs anyway, and it works fine that way. But it's not working for ID. If the above is the correct location for the fix I can create a pull request. Just wanted to check back if I'm understanding this correctly.

@Murthy10
Copy link

I'm facing the same issue is there any progress?

@nuarhu
Copy link
Author

nuarhu commented Sep 22, 2018

We developed our own layer instead of using graphene-django. Unfortunately, we are still stuck with the staticmethods and classmethods and init_with_subclass instead of a decent way of extending the base classes. It's a pain and performance is an issue.

@Murthy10
Copy link

On the client side I'm using React and Apollo GraphQL to do the mutation.
After some fiddling around I have a hacky solution for my problem.
I decode the base 64 Id and use the global Id.

let id = window.atob(id).split(':').pop();

Maybe this could help someone until the issue is fixed.

@alexnitta
Copy link

alexnitta commented Oct 1, 2018

I found the basis of my solution in this comment: graphql-python/graphene#243 (comment)

It looks like the idea is to extend the graphene.relay.node class to change the default behavior of base-64 encoding the primary key.

Here's an example where I'm using a UUID for the primary key, but I expect this would work with an integer primary key as well.

# models.py

import uuid

from django.db import models
from graphene.relay import Node


class UUIDModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    
class Person(UUIDModel):
    first_name = models.CharField(max_length=50, blank=True)
    last_name = models.CharField(max_length=50, blank=True)


class CustomNode(Node):  # extends graphene.relay.Node and returns a non-encoded ID
    class Meta:
        name = 'Node'
    
    @staticmethod
    def to_global_id(type, id):
        return id


# schema.py

import graphene
import django_filters
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField

from .models import Person, CustomNode


class PersonType(DjangoObjectType):
    class Meta:
        model = Person


class PersonFilter(django_filters.FilterSet):
    class Meta:
        model = Person
        fields = ['first_name', 'last_name']


class PersonNode(DjangoObjectType):
    class Meta:
        model = Person
        interfaces = (CustomNode,)


class CreatePerson(graphene.relay.ClientIDMutation):
    person = graphene.Field(PersonNode)

    class Input:
        first_name = graphene.String()
        last_name = graphene.String()

    def mutate_and_get_payload(root, info, **input):

        person = Person(
            first_name=input.get('first_name'),
            last_name=input.get('last_name'),
        )
        person.save()

        return CreatePerson(person=person)


class Query(graphene.ObjectType):
    person = graphene.relay.Node.Field(PersonNode)
    persons = DjangoFilterConnectionField(PersonNode,
                                          filterset_class=PersonFilter)


class Mutation(graphene.AbstractType):
    create_person = CreatePerson.Field()

@citadelgrad
Copy link

citadelgrad commented Jan 31, 2019

Summary: I believe you only need to use interfaces = (relay.Node,) if you are using React-Relay's javascript framework.

I removed the interfaces option under Meta, now my site returns the integer instead of the hash. As best as I can tell using Relay's Node Interface helps detect the field types from your models or database.

Read more about interfaces.
https://docs.graphene-python.org/en/latest/types/interfaces/
https://github.com/graphql-python/graphene/blob/master/graphene/types/interface.py
"""
Interface Type Definition
When a field can return one of a heterogeneous set of types, a Interface type
is used to describe what types are possible, what fields are in common across
all types, as well as a function to determine which type is actually used
when the field is resolved.
"""

It appears the reason for Relay's Node conversion to a hashed ID is to create a globally unique ID.

The Node interface and node field assume globally unique IDs for this refetching. A system without globally unique IDs can usually synthesize them by combining the type with the type-specific ID, which is what was done in this example.

source: https://facebook.github.io/relay/docs/en/graphql-server-specification.html

@citadelgrad
Copy link

IMO this issue should be closed and the documentation updated to explain how these hashed IDs are being created.

@stale
Copy link

stale bot commented Jun 11, 2019

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.

@stale stale bot added the wontfix label Jun 11, 2019
@stale stale bot closed this as completed Jun 18, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants