Flask SQLAlchemy one to one one to many practice

  • 2020-04-02 09:44:12
  • OfStack

Flask-SQLAlchemy installation and tabling please (link: #).


# Role table 
class Role(db.Model):
    id=db.Column(db.Integer,primary_key=True)
    name=db.Column(db.String(80))

# RoleType table 
class Role_type(db.Model):
    query_class=Common_list_name_Query
    id=db.Column(db.Integer,primary_key=True)
    name=db.Column(db.String(120))

One to one
Just change the definition in the property


# Role table 
class Role(db.Model):
    role_type_id=db.Column(db.Integer,db.ForeignKey('role_type.id'))

role=db.relationship('Role',backref='role_type',lazy='dynamic', uselist=False)

More than a pair of


#  One-to-many needs to fill in the relationship between the two tables 
class Role(db.Model):
    role_type_id=db.Column(db.Integer,db.ForeignKey('role_type.id'))

class Role_type(db.Model):
    roles=db.relationship('Role',backref='role_type',lazy='dynamic')

Specific parameters can be referred to the following documents:
(link: http://flask.pocoo.org/docs/patterns/sqlalchemy/)
(link: http://packages.python.org/Flask-SQLAlchemy/)


Related articles: