Flask sqlalchemy many-to-many insert data

You don’t need to add anything directly to your association table, SQLAlchemy will do that. This is more or less from SQLAlchemy documentations: association_table = db.Table(‘association’, db.Model.metadata, db.Column(‘left_id’, db.Integer, db.ForeignKey(‘left.id’)), db.Column(‘right_id’, db.Integer, db.ForeignKey(‘right.id’)) ) class Parent(db.Model): __tablename__ = ‘left’ id = db.Column(db.Integer, primary_key=True) children = db.relationship(“Child”, secondary=association_table) class Child(db.Model): __tablename__ = ‘right’ id = db.Column(db.Integer, … Read more

SQLAlchemy ManyToMany secondary table with additional fields

You will have to switch from using a plain, many-to-many relationship to using an “Association Object”, which is basically just taking the association table and giving it a proper class mapping. You’ll then define one-to-many relationships to User and Community: class Membership(db.Model): __tablename__ = ‘community_members’ id = db.Column(‘id’, db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey(‘user.id’)) community_id … Read more

Flask Download a File

You need to make sure that the value you pass to the directory argument is an absolute path, corrected for the current location of your application. The best way to do this is to configure UPLOAD_FOLDER as a relative path (no leading slash), then make it absolute by prepending current_app.root_path: @app.route(‘/uploads/<path:filename>’, methods=[‘GET’, ‘POST’]) def download(filename): … Read more

Flask-SQLalchemy update a row’s information

Retrieve an object using the tutorial shown in the Flask-SQLAlchemy documentation. Once you have the entity that you want to change, change the entity itself. Then, db.session.commit(). For example: admin = User.query.filter_by(username=”admin”).first() admin.email=”[email protected]” db.session.commit() user = User.query.get(5) user.name=”New Name” db.session.commit() Flask-SQLAlchemy is based on SQLAlchemy, so be sure to check out the SQLAlchemy Docs as … Read more

How to update SQLAlchemy row entry?

There are several ways to UPDATE using sqlalchemy 1) user.no_of_logins += 1 session.commit() 2) session.query(User).\ filter(User.username == form.username.data).\ update({‘no_of_logins’: User.no_of_logins + 1}) session.commit() 3) conn = engine.connect() stmt = User.update().\ values(no_of_logins=User.no_of_logins + 1).\ where(User.username == form.username.data) conn.execute(stmt) 4) setattr(user, ‘no_of_logins’, user.no_of_logins + 1) session.commit()