2012-04-02 50 views
4

Im使用python框架與sqlalchemy燒瓶。許多使用Flask-SQLAlchemy的程序都會返回原始的sql而不是執行

我的許多一對多看起來像這樣:

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 

任何幫助將大大增加!

感謝

回答

7

你使用懶惰= 「動態」,所以collection.questions是一個Query對象。您需要遍歷它以發出SQL並獲取內容:

list(collection.questions) 
+0

ahaaa! Thansk很多! – Ludvig 2012-04-05 12:13:44

相關問題