【问题标题】:How to access SQL Select results with in api.model factory如何在 api.model 工厂中访问 SQL Select 结果
【发布时间】:2020-04-09 21:28:22
【问题描述】:

目前正在寻找使用 SQLAlchemy 和 Flask-restx 呈现多对多关系的解决方案。

下面我加入了两个表 Class 和 Country,其中 Class 有很多 Country。

我想访问数据库中的其他 Country 字段,在本示例中为 country.name 和 country.iso2。我通过使用 fields.list 并将关系的属性设置为 iso2 在 api.model 中部分地管理了这一点。但是,这允许我拥有 country.name 或 country.iso2 但不能同时拥有。

理想情况下,在此示例中,我希望同时获取 country.iso2 以及 country.name。

任何建议将不胜感激。

SQLAlchemy 模型

class_country = Table(
    'class_country',
    Base.metadata,
    Column('class_id', Integer, ForeignKey('class.id')),
    Column('country_id', Integer, ForeignKey('country.id'))
)

class Country(Base):
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(255), index=True, nullable=False)
    iso2 = Column(String(2), nullable=False)
##

class Class(Base):
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(255), index=True, nullable=False)
##
    # Relationships
    country = relationship('Country', secondary=class_country, lazy='subquery')

Flask-Restx(Flask-Restful)API

model = api.model('Class',{
##
    'country': fields.List(
        fields.String()
    ),
##
})

Result:
##
"country": [
    "Australia",
    "New Zealand"
]
##

model = api.model('Class',{
##
    'country': fields.List(
        fields.String(attribute='iso2')
    ),
##
})

Result:
##
"country": [
    "AU",
    "NZ"
],
##

查询

Class.query.filter_by(name=name).first()

【问题讨论】:

    标签: flask flask-sqlalchemy flask-restful


    【解决方案1】:

    您应该为Country 创建一个模型并使用fields.Nested 将其嵌套在Class 中,例如

    country = api.model('Country',{
      'id': fields.Integer,
      'name': fields.String,
      'iso2': fields.String,
    })
    
    model = api.model('Class',{
        'country': fields.List(
            fields.Nested(country)
        ),
    })
    

    检查 Flask-RESTx documentation 中的确切用法

    【讨论】:

    • 为此干杯,我之前尝试过,但没有得到我想要的结果,按照你的例子得到了我想要的结果。
    猜你喜欢
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多