Flask-SQLAlchemy - 如何将值附加到列?

Flask-SQLAlchemy - How to append a value to a column?

我在 SQL 查询方面完全缺乏知识,这让我现在很苦恼。

在 flask-Sqlalchemy 中,如何在不替换已有值的情况下将值附加到已有值的列?

我尝试了 db.session.merge(user) 和 db.session.add(user),但最终都替换了列中的值。

更准确地说,用户table有一个名为classes_id的列,用于记录他参加的健身房类的"id"字段。因此,随着时间的推移,该字段需要与许多其他 类 "id" 一起更新。

为了以防万一,这里有模型

class Classes(db.Model):
    __tablename__= 'classes'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))
    date = db.Column(db.DateTime)
    participants =  db.relationship('User', backref='classes', lazy='dynamic')
    status = db.Column(db.Integer)  #1 = open, 0 = closed

class User(UserMixin,db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    email = db.Column(db.String(64),unique=True,index=True)
    firstname = db.Column(db.String(64))
    lastname = db.Column(db.String(64))
    fullname = db.Column(db.String(64))
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    password_hash = db.Column(db.String(128))
    member_since = db.Column(db.DateTime(), default=datetime.utcnow)
    last_seen = db.Column(db.DateTime(), default=datetime.utcnow)
    notes = db.Column(db.Text())
    classes_id = db.Column(db.Integer, db.ForeignKey("classes.id"))

还有 views.py

@main.route('/add_attendees/<int:class_id>',methods=['GET','POST'])
@login_required
def add_attendees(class_id):
    form = Find_member()
    if form.validate_on_submit():
        fullname = form.member_name.data
        find_username = fullname.find('-')
        username = fullname[find_username + 2:]
        user = User.query.filter_by(username=username).first()
        user.classes_id = class_id          
        db.session.merge(user)
        db.session.commit()
    return redirect(url_for('.add_attendees',class_id = class_id))
return render_template('members_list.html',form=form)

您的模型定义不是您真正想要的。 User.classes_id 只定义一个值。正确答案取决于要求。必须有什么类型的关系?许多 User 到许多 Classes (M:M)?在这种情况下,您将创建如下模型:

user_to_classes = Table('user_to_classes', Base.metadata,
    Column('class_id', Integer, ForeignKey('class.id')),
    Column('user_id', Integer, ForeignKey('user.id'))
)

class Class(Base):
    ...
    # your old wrong code
    # participants = ...
    # here is right definition
    participants = relationship(
        'User', secondary=user_to_classes, backref='classes')

# In the User class you should not write any foreign keys and relations.
# There will be `classes` field defined in backref of `Class.participants

您可以通过以下方式将用户添加到 class:

user = ...# some code that creates or selects a user
class_ = ...# some code that creates or selects a class
# here is the addition
class_.participants.append(user)
session.commit()

查看有关 relationships 的 Sqlalchemy 文档。