我们使用Django和django-graphene提供GraphQL API。我们在模型中有UUID主键。如何妥善处理?
答案 0 :(得分:0)
基于DjangoObjectType
很容易处理id序列化(查询)的事实,我将假设您的问题与突变有关。
此外,由于良好实践是针对在服务器端生成id的,所以我也将忽略您提到UUID的事实:我觉得应该在graphql层之外处理此逻辑。
因此,我们似乎只剩下一个问题:
是否有一个graphene-django输入字段来验证用作突变参数的主键?
找不到关于它的任何文档,所以我冒险以下内容:
def PrimaryKey(model: django.db.models.Model):
""" This contrived way of creating PrimaryKey classes is due to the fact that
parse_literal is a static method of graphene.Scalar.
"""
def parse_literal(node):
if isinstance(node, ast.IntValue):
pk = node.value
elif isinstance(node, ast.StringValue):
pk = int(node.value)
else:
raise GraphQLError(f'Unsupported type for PrimaryKey: {type(node)}')
return model.objects.get(pk=pk)
return type(
f'{model.__name__}PrimaryKey',
(graphene.Scalar,),
dict(
parse_literal=parse_literal,
serialize=lambda x: None,
parse_value=lambda x: None,
)
)
使用建议(并非所有型号均显示):
class CreateProject(graphene.Mutation):
class Arguments:
name = graphene.String()
owner = PrimaryKey(User) # graphene.List(PrimaryKey(User)) works too
ok = graphene.Boolean()
@staticmethod
def mutate(root, info, name: str, owner: User): # owner has been instantiated
pass # do business