Skip to content

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

Open
@thomas-arun

Description

@thomas-arun

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?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions