【问题标题】:Flask-SQLAlchemy: relationship querying and nested object dataFlask-SQLAlchemy:关系查询和嵌套对象数据
【发布时间】:2018-08-22 20:32:43
【问题描述】:

我正在使用 Flask-SQLAlchemy 玩 python RESTful-API 我在查询 2 个表之间的 1-M 关系时得到了结构,例如 Location(1) 可能有很多 Buildings(m) 这就是我所做的(我的项目结构):

project 
     model
         __init__.py
         location.py
         building.py
    resource     
         __init__.py
         location.py
         building.py
    schema
         __init__.py
         schema.py     
     app.py
     database.py 

这是我的模型:

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')

这是我的资源:

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)

当我尝试“获取”/BuildingList 时,没有错误,但在 Location() 模型中未完成。这就是我得到的“location_code”:[{},{},{},{},{},{},{},{}], 它完全 NULL

我正在尝试寻找嵌套对象的结果,例如 Building{building_code:"X",building_name:"Y",building_type:"Z",location_code:{LocationModel}}
我尝试打印buildingModel.query - 它已经是SQL加入命令我认为问题出在映射对象上,我的理解可能是我错了。

【问题讨论】:

    标签: python sqlalchemy flask-sqlalchemy marshmallow


    【解决方案1】:

    要查询数据库,您必须首先在 Flask 代码中创建其类定义的对象。

    应从您的代码中查询class Buildingclass Location。所以应该是这样的:

    class BuildingList(Resource):
    def get(self):
        buildings = Building.query.all()
        results = buildings_schema.dump(buildings)
        print(results)
    
    class LocationList(Resource):
    def get(self):
        locations = Location.query.all()
        results = locations_schema.dump(locations)
        print(results)
    

    我在您的代码中没有看到任何 buildingModellocationModel 的定义。

    【讨论】:

    • 谢谢,哦,我忘了告诉你。是的,我已经用 locationModel = Location() 和 buildingModel = Building() 做到了。
    • 我也没有看到你的 Flask 路由。如果您启用了 Flask 调试,您将在控制台中收到调试消息。请也添加这些消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 2019-10-16
    相关资源
    最近更新 更多