我正在使用 python 包 Flask、SQLAlchemy、Graphene 和 Graphene-SQLAlchemy 构建 GraphQL API。我遵循了SQLAlchemy + Flask 教程。我能够执行查询和突变来创建记录。现在我想知道更新现有记录的最佳方法是什么。
这是我当前的脚本schema.py:
from graphene_sqlalchemy import SQLAlchemyObjectType
from database.batch import BatchOwner as BatchOwnerModel
import api_utils # Custom methods to create records in database
import graphene
class BatchOwner(SQLAlchemyObjectType):
"""Batch owners."""
class Meta:
model = BatchOwnerModel
interfaces = (graphene.relay.Node,)
class CreateBatchOwner(graphene.Mutation):
"""Create batch owner."""
class Arguments:
name = graphene.String()
# Class attributes
ok = graphene.Boolean()
batch_owner = graphene.Field(lambda: BatchOwner)
def mutate(self, info, name):
record = {'name': name}
api_utils.create('BatchOwner', record) # Custom methods to create records in database
batch_owner = BatchOwner(name=name)
ok = True
return CreateBatchOwner(batch_owner=batch_owner, ok=ok)
class Query(graphene.ObjectType):
"""Query endpoint for GraphQL API."""
node = graphene.relay.Node.Field()
batch_owner = graphene.relay.Node.Field(BatchOwner)
batch_owners = SQLAlchemyConnectionField(BatchOwner)
class Mutation(graphene.ObjectType):
"""Mutation endpoint for GraphQL API."""
create_batch_owner = CreateBatchOwner.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
评论:
- 我的对象
BatchOwner
只有 2 个属性(ID、名称) - 为了能够更新
BatchOwner
名称,我假设我需要提供数据库 ID(而不是中继全局 ID)作为某些更新方法的输入参数 - 但是当我从我的客户那里查询 a 时
BatchOwner
,Graphene 只返回我使用 base64 编码的全局 ID(例如:QmF0Y2hPd25lcjox
,对应于BatchOwner:1
)
响应示例:
{
"data": {
"batchOwners": {
"edges": [
{
"node": {
"id": "QmF0Y2hPd25lcjox",
"name": "Alexis"
}
}
]
}
}
}
我目前正在考虑的解决方案是:
- 创建一个以全局 ID 作为参数的更新突变
- 解码全局 ID(如何?)
- 使用解码后的全局Id检索到的数据库Id对数据库进行查询并更新对应的记录
有一个更好的方法吗?