Currently looking for a solution to rendering a many to many relationship using SQLAlchemy and Flask-restx.
Below I am joining two tables Class and Country where Class has many Countries.
I want to gain access to the other Country fields in the database, in this example country.name and country.iso2. I have partially managed this in the api.model by using fields.list and setting the attribute for the relationship to iso2. However this allows me to either have country.name or country.iso2 but not both.
Ideally in this example I want to get country.iso2 as well country.name.
Any advise would be appreciated.
SQLAlchemy Models
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"
],
##
Query
Class.query.filter_by(name=name).first()
You should create a model for Country
and nest it in Class
using fields.Nested
such as
country = api.model('Country',{
'id': fields.Integer,
'name': fields.String,
'iso2': fields.String,
})
model = api.model('Class',{
'country': fields.List(
fields.Nested(country)
),
})
Check the exact usage in the Flask-RESTx documentation