官术网_书友最值得收藏!

Base model

SQLAlchemy is most famous for its object-relational mapper (ORM), an optional component that provides the data mapper pattern, where classes can be mapped to the database in open-ended, multiple ways, allowing the object model and database schema to develop in a cleanly decoupled way from the beginning. We are using the Flask-SQLAlchemy extension here, which extends the support of SQLAlchemy. Flask-SQLAlchemy enhances the features that may need to be integrated with the Flask application.

We are going to combine the generic SQL operations which are required to interact by using Flask-SQLAlchemy. Hence, we are going to create a base model class and will use this class for other modules' model classes. That's the reason we are putting it under the config directory. Here is the models.py file.

File—config/models.py:

from app import db


class BaseModel:
"""
Base Model with common operations.
"""

def delete(self):
db.session.delete(self)
db.session.commit()

def save(self):
db.session.add(self)
db.session.commit()
return self

You can see here that we group the database operations that are required by all models. The db instance was created in the app/__init__.py file using the Flask-SQLAlchemy extension.

Here, we have implemented the save and delete methods. db.Model defines a generic pattern to create a model class that represents the database table. In order to save and delete, we need to follow some predefined operations such as db.session.add(), db.session.delete(), and db.session.commit().

So, we grouped the generic operations under the save and delete methods. These methods will be called from a model class that will inherit them. We will look at this later when we create a model class by extending BaseModel.

主站蜘蛛池模板: 昌宁县| 乐安县| 洪洞县| 湄潭县| 穆棱市| 平陆县| 车险| 横山县| 佛学| 合作市| 东方市| 东兰县| 农安县| 辛集市| 公主岭市| 衡东县| 九龙城区| 商河县| 横峰县| 罗山县| 原阳县| 大宁县| 遂昌县| 醴陵市| 塔城市| 宁德市| 山东省| 商河县| 丰宁| 离岛区| 中江县| 桐乡市| 玉门市| 杨浦区| 山阳县| 安新县| 佛坪县| 恩平市| 将乐县| 临泽县| 郴州市|