【问题标题】:How to deal with django-graphene with UUID primary keys in django?如何在 django 中使用 UUID 主键处理 django-graphene?
【发布时间】:2018-10-29 00:32:41
【问题描述】:

我们使用 Django 和 django-graphene 来提供 GraphQL API。我们在模型中有 UUID 主键。如何妥善处理?

【问题讨论】:

  • 您能否提供更多有关您的架构和模型设置的信息?另外,“妥善处理”是什么意思?目前它不适合您吗?

标签: python django graphql graphene-python


【解决方案1】:

基于 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

【讨论】:

    猜你喜欢
    • 2019-09-20
    • 2021-02-07
    • 2018-03-31
    • 2019-09-22
    • 2017-11-11
    • 2020-05-24
    • 2017-12-26
    • 2020-04-13
    • 2021-11-09
    相关资源
    最近更新 更多