如何减少草莓GraphQl和FastApi中一对一关联的数据库查询数量?

发布于 2025-01-28 11:02:53 字数 331 浏览 4 评论 0原文

我正在使用FastAPI和Strawberry开发Python GraphQl API服务器,并且正在实现此功能: 我有两个实体,即用户和订单,它们具有一对多关联(用户可以有很多订单,订单只能有一个用户),我想获取一个用户列表,每个订单列表。

如果我要用简单的休息端点来实现此功能,我可以进行第一个查询以获取用户,然后在Python代码中进行第二个查询,以获取订单,并根据每个订单属于的用户基于外国订单属于钥匙值。

不过,使用草莓GraphQl,看来我无法避免为每个用户进行查询,鉴于,即使使用数据加载器模式,我仍然需要事先知道订单ID,这使响应时间较慢。

有解决这个问题的解决方案吗?我的方法完全错了吗?

I'm developing a python GraphQL API server using FastAPI and Strawberry, and I'm implementing this feature:
I have two entities, User and Order, which have a one to many association (a User can have many Orders, an Order can only have one User), and I want to get a list of users, each with the list of their orders.

If I were to implement this with a simple REST endpoint, I could make a first query to get the users and then a second query to fetch the orders, sorting out, in the python code, which user each order belongs to based on the foreign key value.

Using Strawberry GraphQL though, it seems I cannot avoid making a query for each user, given that, even using the data loader pattern I would still need to know the order ids beforehand, and this is making the response time much slower.

Is there a solution to this problem? Is my approach completely wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伴梦长久 2025-02-04 11:02:53

数据加载器功能本身可以进行分组。

async def load_orders_by_user(keys: list[int]) -> Iterable[list[Order]]:
    orders = # select * from order where user_id in keys
    groups = {key: [] for key in keys}  # dict maintains order
    for order in orders:
        groups[order.user_id].append(order)
    return groups.values()

该想法上的变体:

  • 加载程序还可以同时加载用户,而
  • 加载程序可以将订单排序 IDS ,并使用其他数据加载程序进行订单

The data loader function itself can do the grouping.

async def load_orders_by_user(keys: list[int]) -> Iterable[list[Order]]:
    orders = # select * from order where user_id in keys
    groups = {key: [] for key in keys}  # dict maintains order
    for order in orders:
        groups[order.user_id].append(order)
    return groups.values()

Variants on that idea:

  • the loader could also load the users at the same time
  • the loader could group order ids only and use a different data loader for orders
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文