graphql-python / graphql-python/graphene-django

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

Open
#1,414 0 comments 1 reaction 0 assignees View on GitHub
✨enhancement
Dominant language
Python
Stars
4.4k
Forks
760
PR merge metrics
No merged PRs in 30d

Description

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?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.