推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
honmaple
V2EX  ›  Python

sqlalchemy 使用上的小 tips

  •  
  •   honmaple · Feb 8, 2017 · 2374 views
    This topic created in 3516 days ago, the information mentioned may be changed or developed.

    1.sqlalchemy object 序列化为 json

    posts = Post.query.all()
    serializer = Serializer(posts,many=True)
    data = serializer.data
    

    2.像 django orm 一样使用 sqlalchemy

    posts = Post.query.filter_by(id__in=['1','2','3'],tags__name='sqlalchemy').order_by('-id').all()
    

    3.去掉一些 sqlalchemy 的重复工作

    # 关联用户表
    class Post(ModelUserMixin, Model):
        
        user_related_name = 'posts'
        titile = ...
    

    地址:https://github.com/honmaple/maple-json

    代码很简单,没写注释应该也能看懂,感觉不错,所以分享出来一下

    4 replies  •  2017-02-11 23:42:26 +08:00
    whnzy
        1
    whnzy  
       Feb 8, 2017
    不如在 PostModel 加一个 to_json 方法。
    junnplus
        2
    junnplus  
       Feb 8, 2017
    @whnzy +1
    honmaple
        3
    honmaple  
    OP
       Feb 11, 2017 via Android
    @whnzy @junnplus 当然可以自定义一个 to_json 的方法,但这样的话工作量不是要增加很多吗?我当时的初衷就是不用自己写,就可以快速序列化 object 生成 json(其实是看了 django rest framework Serializer 的设计,想实现一个类似的东西)
    junnplus
        4
    junnplus  
       Feb 11, 2017 via iPhone
    to_json 放在 basemodel 就行。。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2520 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 105ms · UTC 01:45 · PVG 09:45 · LAX 18:45 · JFK 21:45
    ♥ Do have faith in what you're doing.