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
Braid
V2EX  ›  Python

sqlalchemy 查询提示“TypeError: expected string or Unicode object, int found”

  •  
  •   Braid · 2018-06-14 15:47:38 +08:00 · 1527 次点击
    这是一个创建于 2114 天前的主题,其中的信息可能已经有所发展或是发生改变。

    RT

    我的 model 之前是这样的:

    class Blog(Base):
        __tablename__ = 'blog'
        id = Column(Integer,primary_key=True)
        title = Column(String(200))
        add_time = Column(DateTime, default=datetime.now)
        update_time = Column(DateTime, default=datetime.now)
    
        def __repr__(self):
            return "%d" % (self.id)
    

    然后我创建了 sqlalchemy 的 db session,去查询这个表的语句如下:

    db.query(Blog).filter_by(id=1).first()

    发现报错“ TypeError: expected string or Unicode object, int found ”

    然后我开始是怀疑 def repr(self):的问题,网上有提示说不支持 int 类型,那么我将 model 里的 id 改成了字符串类型,如下:

    class Blog(Base):
        __tablename__ = 'blog'
        id = Column(String(50),primary_key=True)
        title = Column(String(200))
        add_time = Column(DateTime, default=datetime.now)
        update_time = Column(DateTime, default=datetime.now)
    
        def __repr__(self):
            return "%s" % (self.id)
    

    但还是报错,真的很囧,求大佬帮助,十分感谢!

    linuxchild
        1
    linuxchild  
       2018-06-14 15:54:54 +08:00   ❤️ 1
    id='1' 试一下
    Braid
        2
    Braid  
    OP
       2018-06-14 15:55:43 +08:00
    @linuxchild 对 改成 string 后就是这么查询的,还是一样的报错
    linuxchild
        3
    linuxchild  
       2018-06-14 15:58:10 +08:00   ❤️ 1
    @Braid 看一下之前的表,去看看表中字段类型
    Braid
        4
    Braid  
    OP
       2018-06-14 16:02:05 +08:00
    @linuxchild 你好,我发现 db.query(Blog.name).filter_by(id=1).first()和 db.query(Blog.id).filter_by(id=1).first()这样是没问题的
    Braid
        5
    Braid  
    OP
       2018-06-14 16:42:58 +08:00
    问题解决了,自己也备注下吧,原来是对 sqlalchemy 数据类型使用不够深入导致的
    有个字段是 type = Column(ChoiceType(TYPES),default=6666),然后 TYPES=[
    (0, u"情感"),
    (1, u"生活"),
    (2, u"编码"),
    (6666, u"其它")
    ]

    如果是这种 int 类型的一一对应,那么正确的使用方式是 type = Column(ChoiceType(TYPES,Integer()),default=6666)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1041 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 22:32 · PVG 06:32 · LAX 15:32 · JFK 18:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.