Flask SQLAlchemy 多级外键 JOIN 查询:示例和指南
To perform a multi-level foreign key join and retrieve data using Flask and SQLAlchemy, you can use the following code:\n\npython\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'your_database_uri'\ndb = SQLAlchemy(app)\n\nclass HandleGaochabiaoComparisonResult(db.Model):\n __tablename__ = 'handle_gaochabiao_comparison_result'\n id = db.Column(db.Integer, primary_key=True)\n zhenduan_id = db.Column(db.Integer, db.ForeignKey('zhenduan.id'))\n # ...\n\nclass HandleGaochabiaoCezhan(db.Model):\n __tablename__ = 'handle_gaochabiao_cezhan'\n id = db.Column(db.Integer, primary_key=True)\n # ...\n\nclass CeduansDetails(db.Model):\n __tablename__ = 'ceduans_details'\n id = db.Column(db.Integer, primary_key=True)\n gaochabiao_match_id = db.Column(db.Integer, db.ForeignKey('handle_gaochabiao_matchs.id'))\n # ...\n\nclass Zhenduan(db.Model):\n __tablename__ = 'zhenduan'\n id = db.Column(db.Integer, primary_key=True)\n # ...\n\n@app.route('/')\ndef query_data():\n result = HandleGaochabiaoComparisonResult.query\n .join(HandleGaochabiaoCezhan)\n .join(CeduansDetails, HandleGaochabiaoMatchs.ceduans_details)\n .join(Zhenduan, HandleGaochabiaoComparisonResult.zhenduan_id == Zhenduan.id)\n .all()\n\n # Process the result as needed\n # ...\n\n return 'Data retrieved successfully'\n\nif __name__ == '__main__':\n app.run()\n\n\nMake sure to replace 'your_database_uri' with the actual URI of your database. Also, adjust the table and column names according to your database schema.\n\nThis code defines the necessary models for each table involved in the join and configures the Flask application and SQLAlchemy. The query_data function performs the join and returns the result. You can process the retrieved data as needed.\n\nNote: The code assumes that you have already defined the HandleGaochabiaoMatchs model, as it is not included in your question.
原文地址: https://www.cveoy.top/t/topic/qeOE 著作权归作者所有。请勿转载和采集!