GraphQL 查询 return 不可迭代

GraphQL Query to return non-iterable

我在 python 中使用 strawberry-graphql,并且查询 return 是 User

的列表
@strawberry.type
class User:
    email: str
    name: str

def get_user():
    items = get_from_database()
    return items

@strawberry.type
class Query:
    all_user: List[User] = strawberry.field(resolver=get_user)

schema = strawberry.Schema(Query)

它工作正常,但我想要一些额外的属性,例如 total_item:

def get_user():
    items = get_from_database()
    return {
        'items': items
        'total_item': len(items)
    }

在上面的代码中,Strawberry 将 dict 转换为字符串,所以没有成功。我尝试创建模式:

@strawberry.type
class User:
    email: str
    name: str

@strawberry.type
class GetUserResult:
    items: List[User]
    item_count: int

def get_user():
    items = get_from_database()
    return GetUserResult(
        items = items
        item_count = len(items)
    )

但是它说查询必须 return 一个可迭代的 (Expected Iterable, but did not find one for field 'Query.allUser'.)。

有什么办法吗?

固定示例如下:

from typing import List
import strawberry

@strawberry.type
class User:
    email: str
    name: str

def get_user():
    items = [User(email="email", name="Pat")]
    return GetUserResult(
        items=items,
        item_count=len(items)
    )

@strawberry.type
class User:
    email: str
    name: str

@strawberry.type
class GetUserResult:
    items: List[User]
    item_count: int

@strawberry.type
class Query:
    all_user: GetUserResult = strawberry.field(resolver=get_user)

schema = strawberry.Schema(Query)

你可以test here too.

问题是在您定义的第二个片段中:

def get_user():
    items = get_from_database()
    return GetUserResult(
        items = items
        item_count = len(items)
    )

但查询仍需要用户列表

@strawberry.type
class Query:
    all_user: List[User] = strawberry.field(resolver=get_user)