• Pydantic如何分离field和alias


    问题分析

    即假如需要返回的是:

    {
        "isStar": ture
    }
    

    在python中一般不使用isStar这种命名方式, 所以我们需要使用别名定义模型:

    class TestModel(BaseCategoryModel):
        is_star: bool = Field(..., alias="isStar")
    

    而且在SQLAlchemy中也要定义相关字段, 也是由于命名的习惯性, 定义为:

    class Test(Base):
        __tablename__ = 'Test'
        is_star = Column(Boolean, nullable=False, default=False, comment="是否星标"
    

    但是假如我们直接让Pydantic从ORM中读取数据的话, 会报错, 原因也很简单

    问题解决

    TestModel这个模型接收和输出的都是别名后的字段, 即isStar
    Test这个表中没有该字段, 所以会报错!

    也就是说, 只需要我们让Pydantic输出isStar但接收的是is_star , 不就完美解决了吗!
    为此我去Github上看了一下Issues: #2429, 发现了一个差不多的issue, 然后看了一下官方文档:
    发现了allow_population_by_field_name配置( 在v1.0之前是allow_population_by_alias), 该配置为: 别名字段是否可以 由模型属性给出的名称以及别名填充
    所以修改后的TestModel模型为:

    class TestModel(BaseCategoryModel):
        is_star: bool = Field(..., alias="isStar")
    	
        class Config:
            orm_mode = True
            allow_population_by_field_name = True
    

    如此便可以让TestModel接收is_star 而返回的是isStar

  • 相关阅读:
    The model backing the 'XXX' context has changed 错误
    MVC5+EF6 入门完整教程四
    MVC5 + EF6 完整入门教程三
    MVC5 + EF6 入门完整教程二
    每日总结9.11
    setTextColor的几个注意事项
    selector使用注意事项
    每日总结9.9
    android popWindow使用注意事项
    有关TextView的drawaleTop属性
  • 原文地址:https://www.cnblogs.com/lczmx/p/15904536.html
Copyright © 2020-2023  润新知