简体   繁体   English

如何在 python 中使用石墨烯-pydantic 和石墨烯的子类中的 pydantic 模型?

[英]How to use pydantic models in subclass with graphene-pydantic and graphene in python?

Use Case Scenario用例场景

I've two pydantic models.我有两个 pydantic 模型。 Each in his own module (file).每个人都有自己的模块(文件)。 One Model, the TUser depends on the TAddress .一个 Model, TUser依赖于TAddress

address_model.py地址模型.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用户模型.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]

If I use the TUser model know for my PydanticObjectType如果我使用TUser model 知道我的 PydanticObjectType

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

I get the following error message:我收到以下错误消息:

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'>)

It seems like that there is a problem when using pydantic models from different modules that depends on each other.使用来自彼此依赖的不同模块的 pydantic 模型时似乎存在问题。 What is the solution for this use case?这个用例的解决方案是什么?

Any idea?任何想法?

The error message gives you the hint you need.错误消息为您提供所需的提示。

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

What's happening is that Graphene doesn't know how to convert the address class to be able to use it with the TUser because it is part of the PydanticObject .发生的事情是 Graphene 不知道如何转换地址 class 以便能够与TUser一起使用它,因为它是PydanticObject的一部分。

In order to get rid of your error, you need to define a PydanticObjectType referring to TAddress , this way Graphene will know what is the relationship between these two objects.为了摆脱你的错误,你需要定义一个引用PydanticObjectTypeTAddress ,这样 Graphene 就会知道这两个对象之间的关系是什么。

In your schema file where you have the UserType just do this:在您拥有UserType的架构文件中,只需执行以下操作:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM