如何在 api.model 工厂中访问 SQL Select 结果

How to access SQL Select results with in api.model factory

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

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

我想访问数据库中的其他国家/地区字段,在本例中为 country.name 和 country.iso2。我在 api.model 中通过使用 fields.list 并将关系的属性设置为 iso2 来部分管理此操作。但是,这使我可以拥有 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()

您应该为 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