python - 多对多使用 Flask-SQLAlchemy 返回原始 sql 而不是执行

标签 python sqlalchemy flask flask-sqlalchemy

我将 python 框架 flask 与 sqlalchemy 结合使用。

我的多对多看起来像这样:

collections_questions = db.Table('collections_questions',
         db.Column('question_id',db.Integer,db.ForeignKey('question.id')),
         db.Column('collection_id',db.Integer,db.ForeignKey('collection.id'))
)
class Collection(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    title = db.Column(db.String)
    lang = db.Column(db.Integer)
    questions = db.relationship('Question',secondary=collections_questions,backref=db.backref('collections'),lazy='dynamic')
    def __init__(self,title,lang=0):
      self.title = title
      self.lang = lang

class Question(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String)
    question = db.Column(db.String)
    lang = db.Column(db.Integer)
    type = db.Column(db.Integer)

    def __init__(self,title,question,lang=0,type=0):
        self.title = title
        self.question = question
        self.lang = lang
        self.type = type

现在如果我这样做

collection = db.session.query(Collection).get(1)

collection.questions 不返回问题列表,而是返回以下查询。

SELECT question.id AS question_id, question.title AS question_title, question.question AS question_question, question.lang AS question_lang, question.type AS question_type 
FROM question, collections_questions 
WHERE :param_1 = collections_questions.collection_id AND question.id = collections_questions.question_id

任何帮助将不胜感激!

谢谢

最佳答案

您使用的是 lazy="dynamic",因此 collection.questions 是一个 Query 对象。您需要对其进行迭代以发出 SQL 并获取内容:

list(collection.questions)

关于python - 多对多使用 Flask-SQLAlchemy 返回原始 sql 而不是执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9969527/

相关文章:

python - 如何修复 bs4 选择错误 : 'TypeError: __init__() keywords must be strings'

python - 如何在numpy中的二维矩阵中随机采样

python - 与继承类的多对一关系

python - sqlalchemy 按计数列过滤

python - 使用 matplotlib 在 python 中使用字典的条形图

python - MySQL "IN"查询中的多个参数

python - 将媒体文件提供到podcast.app(iOS/MacOS)进行下载

flask - Airflow基本身份验证-无法使用创建的用户登录

python - 如何创建只有一个帖子的页面?

python - 从 Thonny : ModuleNotFoundError 导入 numpy