【问题标题】:How to use pydantic models in subclass with graphene-pydantic and graphene in python?python - 如何在python中使用带有graphene-pydantic和graphene的子类中的pydantic模型?
【发布时间】:2021-07-08 22:44:25
【问题描述】:

用例场景

我有两个 pydantic 模型。每个人都有自己的模块(文件)。一个模型,TUser 依赖于 TAddress

address_model.py

class TAddress(BaseModel):
    id: Optional[int]
    address: Optional[constr(max_length=100, strip_whitespace=True)]
    city: Optional[constr(max_length=80, strip_whitespace=True)]
    postal_code: Optional[constr(max_length=15, strip_whitespace=True)]
    country: Optional[constr(max_length=3)]

user_model.py

class TUser(BaseModel):
    id: UUID = None
    email: Optional[EmailStr]

    address: Optional[TAddress]

    is_active: Optional[bool]
    is_email_verified: Optional[bool]
    created_at: Optional[datetime.datetime]

如果我使用 TUser 模型了解我的 PydanticObjectType

class UserType(PydanticObjectType):
    class Meta:
        model = TUser

我收到以下错误消息:

graphene_pydantic.converters.ConversionError: Don't know how to convert the Pydantic field ModelField(name='address', type=Optional[TAddress], required=False, default=None) (<class 'app.address.serializers.TAddress'>)

似乎在使用来自不同模块的相互依赖的 pydantic 模型时存在问题。 这个用例的解决方案是什么?

有什么想法吗?

【问题讨论】:

    标签: python graphql graphene-python pydantic


    【解决方案1】:

    错误消息为您提供所需的提示。

    Don't know how to convert the Pydantic field ModelField(name='address'....
    

    发生的情况是 Graphene 不知道如何将地址类转换为能够与 TUser 一起使用,因为它是 PydanticObject 的一部分。

    为了摆脱你的错误,你需要定义一个PydanticObjectType引用TAddress,这样Graphene就会知道这两个对象之间的关系是什么。

    在您拥有 UserType 的架构文件中执行以下操作:

    class AddressType(PydanticObjectType):
        class Meta:
            model = TAddress
    
    class UserType(PydanticObjectType):
        class Meta:
            model = TUser
    

    【讨论】:

      猜你喜欢
      • 2021-01-07
      • 1970-01-01
      • 2017-11-27
      • 2019-08-27
      • 1970-01-01
      • 2022-01-02
      • 2019-12-10
      • 2020-01-23
      • 1970-01-01
      相关资源
      最近更新 更多