【发布时间】:2018-10-29 00:32:41
【问题描述】:
我们使用 Django 和 django-graphene 来提供 GraphQL API。我们在模型中有 UUID 主键。如何妥善处理?
【问题讨论】:
-
您能否提供更多有关您的架构和模型设置的信息?另外,“妥善处理”是什么意思?目前它不适合您吗?
标签: python django graphql graphene-python
我们使用 Django 和 django-graphene 来提供 GraphQL API。我们在模型中有 UUID 主键。如何妥善处理?
【问题讨论】:
标签: python django graphql graphene-python
基于 ids 序列化(查询)由 DjangoObjectType 直接处理这一事实,我假设您的问题与突变有关。
另外,由于良好的做法是更倾向于在服务器端生成 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
【讨论】: