sqlalchemy使用上的小tip
GitHub地址: https://github.com/honmaple/maple-json
sqlalchemy object序列化为json
灵感来源于 Django REST framework
多个实例
posts = Post.query.all() serializer = Seralizer(posts,many=True) data = serializer.data
单个实例
post = Post.query.first() serializer = Seralizer(post,many=False) data = serializer.data
排除字段
serializer = Seralizer(post,exclude=['title'])
仅包括字段
serializer = Seralizer(post,include=['title'])
关系查询深度
serializer = Seralizer(post,depth=3)
depth
默认为2
增加一些自定义的函数
serializer = Serializer(post,extra=['get_post_count'])
Post
class Post(Model): ...... def get_post_count(self): return 11
可传递参数的函数
class PostSerializer(Serializer): count = Field(source = 'get_post_count',args={'name':'hello'},default=20) class Meta: include = [] depth = 2 include = [] exclude = [] extra = ['count']
像django orm一样使用sqlalchemy
djang orm与sqlalchemy相比,为什么很多人都认为django orm更好用,大概就是因为django orm更方便
基本查询(已实现)
gt
lt
lte
gte
contains
in
exact
iexact
startswith
istartswith
iendswith
endswith
isnull
range
year
month
day
示例:
Post.query.filter_by(title__contains = 'sql').all() Post.query.exclude_by(title__contains = 'sql').all()
关系查询
Post.query.filter_by(tags__name__contains = 'sql').all()
其它
Post.query.filter_by(tags__name__contains = 'sql').or(Post.id == 1,Post.id == 2).all() Post.query.filter_by(tags__name__contains = 'sql').and(Post.id == 1,Post.id == 2).all() Post.query.filter_by(tags__name__contains = 'sql').exists() Post.query.load_only('title')
去掉一些sqlalchemy的重复工作
以flask-sqlalchemy为例,通过继承 models.py 中的Mixin,就可以去除部分重复工作
ModelMixin
自增ID – id
post = Post(·····) post.save() # 保存 post.delete() # 保存
批量操作
bulk_insert
bulk_update
bulk_save
ModelTimeMixin
增加两字段
created_at
数据创建时间
updated_at
数据更新时间
ModelUserMixin
关联用户表,与User表现为多对一关系(即一个用户有多个post)
class Post(ModelUserMixin, Model): user_related_name = 'posts' titile = ...
相关推荐
Guanjs0 2020-11-09
wmsjlihuan 2020-09-15
shishengsoft 2020-09-15
poplpsure 2020-08-17
CyborgLin 2020-08-15
Richardxx 2020-07-26
sunnyhappy0 2020-07-26
knightwatch 2020-07-19
wcqwcq 2020-07-04
chichichi0 2020-06-16
YAruli 2020-06-13
JF0 2020-06-13
84423067 2020-06-12
心丨悦 2020-06-11
zkwgpp 2020-06-04
stoneechogx 2020-06-04
litterfrog 2020-05-30
today0 2020-05-26