Вопрос

Im using the python framework flask with sqlalchemy.

My many-to-many looks like this:

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

Now if i do

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

collection.questions does not return a list of questions, instead it returns the following query.

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

Any help would be greatly apprecieted!

Thanks

Это было полезно?

Решение

you're using lazy="dynamic", so collection.questions is a Query object. You need to iterate over it to emit SQL and get the contents:

list(collection.questions)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top