gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:22:33 25 4
gpt4 key购买 nike

我将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com