【问题标题】:Error in query many-to-many relationship in sqlalchemy using flask使用烧瓶在sqlalchemy中查询多对多关系时出错
【发布时间】:2016-09-28 14:06:16
【问题描述】:

我有两个模型 CoreDrive 和 GamificationTechnique 以及一个多对多关系的生成表。我试图在表 cores_techiques 中做一个简单的查询,但总是得到错误。

AttributeError:“表”对象没有属性“查询”。

我正在使用 python3、flask 和 sqlalchemy。我是初学者,我正在尝试使用此应用程序学习烧瓶。

型号

#many_CoreDrive_has_many_GamificationTechnique
cores_techiques = db.Table('cores_techiques',
db.Column('core_drive_id', db.Integer, db.ForeignKey('core_drive.id')),
db.Column('gamification_technique_id', db.Integer, db.ForeignKey('gamification_technique.id')))

class CoreDrive(db.Model):
id = db.Column(db.Integer(), primary_key=True)
name_core_drive = db.Column(db.String(80), unique=True)
description_core_drive = db.Column(db.String(255))
techniques = db.relationship('GamificationTechnique', secondary=cores_techiques,
   backref=db.backref('core_drives', lazy='dynamic'))

class GamificationTechnique(db.Model):
id = db.Column(db.Integer(), primary_key=True)
name_gamification_technique = db.Column(db.String(80), unique=True)
description_gamification_technique = db.Column(db.String(255))
number_gamification_technique = db.Column(db.Integer())
attributtes = db.relationship('Atributte', secondary=techniques_atributtes,
   backref=db.backref('gamification_techniques', lazy='dynamic'))

路线

@app.route('/profile')
def profile():
my_core_techique = cores_techiques.query.all()
my_user = User.query.first()
my_technique = GamificationTechnique.query.all()
return render_template('profile.html',my_user=my_user,my_technique=my_technique, my_core_techique=my_core_techique)

【问题讨论】:

  • 您不能创建my_core_techique = cores_techiques.query.all(),因为 cores_techiques 是 Table 对象而不是 Model 对象。你想传递给页面的究竟是什么?
  • 我需要该表中的数据

标签: python flask sqlalchemy flask-sqlalchemy


【解决方案1】:

你可以列出所有的CoreDriver,每个对象都有一个GamificationTechnique的列表

cores = CoreDrivers.query.all()
for core in cores:
    print core.techniques

考虑到这一点,您只能将列表cores 用于页面

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-11
    • 2020-11-21
    • 2014-11-02
    • 2021-06-03
    • 2016-06-18
    • 2016-09-06
    • 2011-09-26
    • 1970-01-01
    相关资源
    最近更新 更多