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

Return object instead of string for FK field in SerializerMutation in Graphene Django #1414

Open
thomas-arun opened this issue May 26, 2023 · 0 comments

Comments

@thomas-arun
Copy link

I have two models ProjectType and Project as follows

class ProjectType(Base):
    name = models.CharField(max_length=100, unique=True)

    class Meta:
        db_table = 'project_types'

    def __str__(self):
        return self.name


class Project(Base):
    name = models.CharField(max_length=100, unique=True)
    project_type = models.ForeignKey(ProjectType, on_delete=models.DO_NOTHING, related_name='related_projects')

    class Meta:
        db_table = 'projects'

    def __str__(self):
        return self.code

and I have Mutations for both using SerializerMutation from Grapehene Django

class ProjectTypeMutation(SerializerMutation):
    class Meta:
        serializer_class = ProjectTypeSerializer
        model_operation = ['create', 'update']


class ProjectMutation(SerializerMutation):
    class Meta:
        serializer_class = ProjectSerializer
        model_operation = ['create', 'update']


class Mutation(graphene.ObjectType):
    cudProjectType = ProjectTypeMutation.Field()
    cudProject = ProjectMutation.Field()

When I perform a create mutation for project, I have to also specify the project_type. The resulting response also has the project_type but as a String. Not an object. Is there any way to get project_type back as an object?

Current Mutation ⬇️

mutation{
  cudProject(input: {name: "Project1" project_type: "1"}) {
    id
    name
    project_type
  }
}

Current Output ⬇️

{
  "data": {
    "cudProject": {
      "id": 200,
      "name": "Project1",
      "project_type": "1"
    }
  }
}

The Solution I would Like

I want project_type to be an object which I can use as follows:

Expected Mutation Request ⬇️ (This brings an error currently)

mutation{
  cudProject(input: {name: "Project1" project_type: "1"}) {
    id
    name
    project_type{
      id
      name
  }
}

Expected Output ⬇️

{
  "data": {
    "cudProject": {
      "id": 200,
      "name": "Project1",
      "project_type": {
         "id": 1,
         "name": "ProjectType1"
    }
  }
}

Is this the default way that is expected from Graphene Django or am I doing something wrong? Any way to do this using SerializerMutation or any other way in Graphene Django?

Or if there is a better way to have Create, Update, Delete Mutations implemented in Graphene Django?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant