I am playing at python RESTful-API with Flask-SQLAlchemy I got struct at querying 1-M relationship between 2 Table, like Location(1) may have many Buildings(m) This is what I did (my project structure):
project
model
__init__.py
location.py
building.py
resource
__init__.py
location.py
building.py
schema
__init__.py
schema.py
app.py
database.py
This is my model:
class Building(db.Model):
__tablename__ = 'building'
building_code = db.Column(db.String(80), primary_key=True)
building_name = db.Column(db.String(80))
building_type = db.Column(db.String(80))
location_code = db.Column(db.Integer,
db.ForeignKey("location.location_code"), nullable=False)
locations = db.relationship("Location", back_populates="buildings",
lazy='joined')
class Location(db.Model):
__tablename__ = 'location'
location_code = db.Column(db.String(80), primary_key=True, nullable=False)
location_name = db.Column(db.String(80))
latitude = db.Column(db.String(80))
longitude = db.Column(db.String(80))
buildings = db.relationship("Building", back_populates="locations",
lazy='joined')
This is my resource:
class BuildingList(Resource):
def get(self):
buildings = buildingModel.query.all()
results = buildings_schema.dump(buildings)
print(results)
class LocationList(Resource):
def get(self):
locations = locationModel.query.all()
results = locations_schema.dump(locations)
print(results)
When I try to "GET" /BuildingList
, there is no error but, not complete in Location()
model. this is what I got "location_code": [{},{},{},{},{},{},{},{}],
It entirely NULL
I am trying and looking for the result as Nested Object like Building{building_code:"X",building_name:"Y",building_type:"Z",location_code:{LocationModel}}
for example.
I try to print buildingModel.query
- It is already SQL joined command I think the problem is in mapping object as my understanding, may I am wrong.