graphene-django 将 models.BigInteger() 转换为 graphene.Integer()

imp*_*oku 1 django graphql graphene-python

我正在使用石墨烯-django。

我正在尝试从models.BigInteger()字段中检索数据,但是当我在 graphiQL 中进行查询时出现错误

{
  "errors": [
    {
      "message": "Int cannot represent non 32-bit signed integer value: 2554208328"
    }
  ],
  "data": {
    "match": null
  }
}
Run Code Online (Sandbox Code Playgroud)

有谁知道我如何强迫石墨烯给我数据?

imp*_*oku 6

我最终使用了自定义标量。如果在 graphene-django 中将其自动转换为更好的标量会更好,但这是我解决此问题的方法。我用自定义 BigInt 标量编写了一个 converter.py 文件,如果我们有一个大于 MAX_INT 的数字,它使用浮点数而不是整数

# converter.py
from graphene.types import Scalar
from graphql.language import ast
from graphene.types.scalars import MIN_INT, MAX_INT

class BigInt(Scalar):
    """
    BigInt is an extension of the regular Int field
        that supports Integers bigger than a signed
        32-bit integer.
    """
    @staticmethod
    def big_to_float(value):
        num = int(value)
        if num > MAX_INT or num < MIN_INT:
            return float(int(num))
        return num

    serialize = big_to_float
    parse_value = big_to_float

    @staticmethod
    def parse_literal(node):
        if isinstance(node, ast.IntValue):
            num = int(node.value)
            if num > MAX_INT or num < MIN_INT:
                return float(int(num))
            return num
Run Code Online (Sandbox Code Playgroud)

然后

# schema.py
from .converter import BigInt
class MatchType(DjangoObjectType):
    game_id = graphene.Field(BigInt)
    class Meta:
        model = Match
        interfaces = (graphene.Node, )
        filter_fields = {}
Run Code Online (Sandbox Code Playgroud)