Some tips for using flask-SQLAlchemy (creation of association relationship)

Flask-SQLAlchemy uses SQLAlchemy directly, but only reduces the function of SQLAlchemy by a large part, and only supports a small part of it. Therefore, when using falsk-SQLAlchemy, it can be used together with the functions in SQLAlchemy.

Here mainly talks about the creation of the relationship between the two databases, and the operations such as add and query under this relationship.

1. Establish an association

class Role(db.Model):
    __tablename__ = 'roles'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    users = db.relationship('User', backref='role')

    def __repr__(self):
        return "<Role %r>"%self.name


class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))

    def __repe__(self):
        return "<User %r>"%self.username

In User, role_id = db.Column (db.Integer, db.ForeignKey ('roles.id')), which is related to the foreign key and id in the
Role table. Users in the Role table = db.relationship (' User ', backref =' role ') represents the connection from the Role table to the User table (a reverse connection relationship)

2. Insert

admin_role = Role(name='Admin')
mod_role = Role(name='Moderator')
user_role = Role(name='User')
user_john = User(username='john', role=admin_role)
user_susan = User(username='susan', role=user_role)
user_david = User(username='david', role=user_role)

db.session.add(admin_role)
db.session.add(mod_role)
db.session.add(user_role)
db.session.add(user_john)
db.session.add(user_susan)
db.session.add(user_david)

db.session.commit()

3. Inquiry

admin_role = Role.get(id)
admin_user = admin_role.role.filter(.....).all()

After the association between the two tables, we can directly through the association relationship between the query results of another table

4. The difference between filter and filter_by

filter_by is a simple query operation

data = Role.query.filter_by(id=123).all()

Filter is a more precise query, in which you can do many complex operations, such as the use of functions in SQL (in, add, or ...)

data = Role.query.filter_by(and_(Role.id == xxx, Role.name == xxx))
Published 190 original articles · 19 praises · 200,000+ views

Guess you like

Origin blog.csdn.net/zengchenacmer/article/details/46995915