简体   繁体   English

Flask-SQLAlchemy append 不适用于多对多关系

[英]Flask-SQLAlchemy append not working for a many to many relationship

I am attempting to use the append method to add to a reference table for a many-to-many relationship between class User and class App (also referred to as 'plus' throughout the code).我正在尝试使用 append 方法将 class 用户和 class 应用程序之间的多对多关系添加到参考表(在整个代码中也称为“加号”)。 The idea is that there will be many users who use a single app and many apps used by a single user so I thought a many to many relationship would be appropriate.这个想法是,会有很多用户使用一个应用程序,而许多应用程序被一个用户使用,所以我认为多对多的关系是合适的。 I am able to get a valid user object and a valid app/plus object but when I use plus.append(user), nothing happens.我能够获得有效用户 object 和有效应用程序/plus object 但是当我使用 plus.append(user) 时,没有任何反应。 I don't get an error and nothing is added to the reference table.我没有收到错误,也没有向参考表添加任何内容。 I am guessing I did not set up the relationship correctly?我猜我没有正确建立关系?

Things I've tried:我尝试过的事情:

  • Changing the direction of the relationship so User is the left side entity.更改关系的方向,使用户成为左侧实体。
  • Making it into a one to many relationship.使其成为一对多的关系。
  • The bi-directional example given in the documentation here . 此处文档中给出的双向示例。
  • The solution here . 这里的解决方案。

Reference table definition:参考表定义:

plusses = db.Table(
'plusses',
db.Column('plus_id', db.Integer, db.ForeignKey('app.id')),
db.Column('user_id', db.Integer, db.ForeignKey('user.id')))

Definition of 'User' class “用户”的定义 class

class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
about_me = db.Column(db.String(140))
last_seen = db.Column(db.DateTime, default=datetime.utcnow)

Definition of 'App' class: “应用程序”class 的定义:

class App(db.Model):
id = db.Column(db.Integer, primary_key=True)
icon = db.Column(db.String(140))
link = db.Column(db.String(140))
name = db.Column(db.String(140))
args = db.Column(db.Text())
description = db.Column(db.String(220))

pluses_user = db.relationship(
        'User', secondary=plusses,backref=db.backref('plusses', lazy='dynamic'), lazy='dynamic')


def __repr__(self):
    return '<App {}>'.format(self.body)

def getApp(self, name):
    return App.query.filter_by(name=name).first()
    # if app is None:
        # Create app here if

def add_plus(self, user):
    if not self.has_plus(user):
        self.pluses_user.append(user)

def remove_plus(self, user):
    if self.has_plus(user):
        self.pluses_user.remove(user)

def has_plus(self, user):
    return self.pluses_user.filter(
        plusses.c.plus_id == user.id).count() > 0

Route that uses the function:使用function的路由:

@bp.route('/add/<plusname>')
@login_required
def add_plus(plusname):
  plus=App.query.filter_by(name=plusname).first()
  if plus is None:
      flash('App not found')
      return redirect(url_for('main.index'))
  plus.add_plus(current_user)
  return redirect(url_for('main.apps'))

I'm new here so please let me know how I can improve my question:) Any help at all would be appreciated.我是新来的,所以请告诉我如何改进我的问题:) 任何帮助都将不胜感激。

I was able to solve this by adding db.session.commit() to my add_plus and remove_plus functions.我能够通过将db.session.commit()添加到我的 add_plus 和 remove_plus 函数来解决这个问题。 They now look like this:他们现在看起来像这样:

def add_plus(self, user):
    if not self.has_plus(user):
        self.pluses_user.append(user)
        db.session.commit()

def remove_plus(self, user):
    if self.has_plus(user):
        self.pluses_user.remove(user)
        db.session.commit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM