我有两个型号
ProjectType
和Project
如下
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
并且我都使用来自 Grapehene Django 的
SerializerMutation
进行了突变
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()
当我为项目执行创建突变时,我还必须指定
project_type
。生成的响应也有 project_type
,但作为字符串。不是一个物体。有什么办法可以让 project_type
恢复为对象吗?
当前突变⬇️
mutation{
cudProject(input: {name: "Project1" project_type: "1"}) {
id
name
project_type
}
}
电流输出⬇️
{
"data": {
"cudProject": {
"id": 200,
"name": "Project1",
"project_type": "1"
}
}
}
我希望project_type是一个可以按如下方式使用的对象:
预期的突变请求⬇️(目前这会带来错误)
mutation{
cudProject(input: {name: "Project1" project_type: "1"}) {
id
name
project_type{
id
name
}
}
预期产出⬇️
{
"data": {
"cudProject": {
"id": 200,
"name": "Project1",
"project_type": {
"id": 1,
"name": "ProjectType1"
}
}
}
有没有办法使用
SerializerMutation
或 Graphene Django 中的任何其他方式来做到这一点?
或者如果有更好的方法在 Graphene Django 中实现创建、更新、删除突变,那也可能会有所帮助。
您可以通过向嵌套模型添加自定义解析器来实现您想要的目的。 顺便说一句,如果您还没有这样做,您还需要为
ProjectType
定义 grahpql 类型。
这是一个简单的例子:
class ProjectTypeType(DjangoObjectType):
class Meta:
model = ProjectType
fields = ('id', 'name')
class ProjectMutation(SerializerMutation):
class Meta:
serializer_class = ProjectSerializer
model_operation = ['create', 'update']
project_type = graphne.Field(ProjectTypeType)
@classmethod
def resolve_project_type(cls, root, info)
return ProjectType.objects.get(pk=root.project_type.pk) # <- NOTE: project_type is PKOnlyObject here
当然,您可能想利用 DataLoaders 来解决 N+1 问题。 PL