My total lack of knowledge in SQL queries is biting me hard right now.
In flask-Sqlalchemy, how to you append a value to a column that already has one without replacing the one already present?
I tried db.session.merge(user) and db.session.add(user) but both end up replacing the value in the column.
To be more precise, the Users table has a column named classes_id that is used to record the "id" field of the gym classes he attended. So that field needs to be updated with many other classes "id" as time goes.
Just in case, here are the models
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"))
And the 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)