Flask-SQLAlchemy操做指南

Flask-SQLAlchemy官方文檔mysql

from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://user:pwd@localhost/school?charset=utf8'

db = SQLAlchemy(app) # 初始化一個對象

class News(db.Model):
__tablename__ = 'wyNews' # WYnews 表的名字
# 表的結構:
id = db.Column(db.Integer,primary_key=True)
title = db.Column(db.String(200),nullable=False)
content = db.Column(db.String(20000),nullable=False)
types = db.Column(db.String(10),nullable=False)
image = db.Column(db.String(300),)
author = db.Column(db.String(20),)
view_count = db.Column(db.Integer,default=1)
create_at = db.Column(db.DateTime,)
is_valid = db.Column(db.Boolean,)

def __repr__(self):
return '<News %r>' % self.title

# 建立表
# db.create_all() #

# 添加數據
new_obj1 = News(
title = 'A1',
content = 'I an A1',
types = '阿里',
)
new_obj2 = News(
title = 'A2',
content = 'I an A2',
types = '阿里',
)

# db.session.add(new_obj1) # 添加數據
# db.session.add(new_obj2)
# db.session.commit()

News.query.filter(News.is_valid==1) # 查詢數據

# 只獲取須要的字段
News.query.with_entities(News.title,News.author).all()
db.session.query(News.title,News.author).all()


News.query.get(1)
Out[90]:
<News '幽遊白書外傳「Two Shots」動畫化決定,講述藏馬和飛影的相遇!'>
News.query.get(1).id
Out[91]:
1

# 經過filter方法取獲得的是BaseQuery,能夠理解爲一個列表,裏面存儲了數據庫中的一條一條記錄,那麼你要取列表中的值,就必須先經過first等方法取出裏面的對象"News" ,而後才能操做對象的屬性
News.query.filter_by(id=1)
Out[92]:
<flask_sqlalchemy.BaseQuery at 0x60b36a0>

News.query.filter_by(id=1).first()
Out[3]:
<News '幽遊白書外傳「Two Shots」動畫化決定,講述藏馬和飛影的相遇!'>
sql

相關文章
相關標籤/搜索