天天看點

sqlalchemy使用上的小tipsqlalchemy object序列化為json像django orm一樣使用sqlalchemy去掉一些sqlalchemy的重複工作

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 = ...