V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2017-02-08 00:56:06 +08:00 · 1621 次点击
    这是一个创建于 2647 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 条回复    2017-02-11 23:42:26 +08:00
    whnzy
        1
    whnzy  
       2017-02-08 17:28:54 +08:00
    不如在 PostModel 加一个 to_json 方法。
    junnplus
        2
    junnplus  
       2017-02-08 23:21:16 +08:00
    @whnzy +1
    honmaple
        3
    honmaple  
    OP
       2017-02-11 19:27:47 +08:00 via Android
    @whnzy @junnplus 当然可以自定义一个 to_json 的方法,但这样的话工作量不是要增加很多吗?我当时的初衷就是不用自己写,就可以快速序列化 object 生成 json(其实是看了 django rest framework Serializer 的设计,想实现一个类似的东西)
    junnplus
        4
    junnplus  
       2017-02-11 23:42:26 +08:00 via iPhone
    to_json 放在 basemodel 就行。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5561 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 05:43 · PVG 13:43 · LAX 22:43 · JFK 01:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.