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

问题描述 投票:0回答:1

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

下面我将两个表连接到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个回答
0
投票

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

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中的确切用法>

© www.soinside.com 2019 - 2024. All rights reserved.