使用Flask-SQLAlchemy的许多人返回原始sql而不是执行

时间:2012-04-02 00:16:22

标签: python sqlalchemy flask flask-sqlalchemy

我正在使用带有sqlalchemy的python框架烧瓶。

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

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

任何帮助都会非常感激!

由于

1 个答案:

答案 0 :(得分:7)

你正在使用lazy =“dynamic”,所以collection.questions是一个Query对象。您需要迭代它以发出SQL并获取内容:

list(collection.questions)