python - 如何在 SQLAlchemy 中使用 postgres 数字范围

标签 python postgresql sqlalchemy

我碰巧找不到很多关于使用 Postgres 的信息SQLAlchemy 中的范围类型不是 this .有谁知道如何将新列值插入到 numrange 列中?有没有人有一些代码片段或比我已经找到的更多的文档?

最佳答案

这已添加到官方文档中:https://bitbucket.org/zzzeek/sqlalchemy/issue/3046/postgresql-range-types-need-better


不得不为此四处挖掘,但如有疑问,请检查测试! SQLAlchemy tests for the range types使用基础 psycopg2 types .

from psycopg2.extras import NumericRange
from sqlalchemy import create_engine, Column, Integer
from sqlalchemy.dialects.postgresql import INT4RANGE
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

engine = create_engine('postgresql:///example', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base(bind=engine)


class Example(Base):
    __tablename__ = 'example'

    id = Column(Integer, primary_key=True)
    window = Column(INT4RANGE, nullable=False)


Base.metadata.create_all()

session.add(Example(window=NumericRange(2, 6)))
session.add(Example(window=NumericRange(4, 8)))
session.commit()

关于python - 如何在 SQLAlchemy 中使用 postgres 数字范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23563736/

相关文章:

postgresql - 如何两次引用外键表?

python - 列表索引超出范围

python - 如何在Python中从Json中获取起源-命运矩阵?

python - 使用 DomainKey 和 Amazon SES 签名的 Django 重置密码电子邮件

javascript - postgresql查询以随机顺序返回

database - 使用 liquibase 将 postgres 表复制到另一个模式

node.js - Windows Node 中 process.env.TZ = 'UTC' 的解决方案?

python - SQLAlchemy - 如何从 ResultProxy 访问列名并写入 CSV header

python - SQLalchemy 查询获取字典的聚合数组

iphone - Google Data/OAuth/AppEngine/Python - 正确注册 Web 应用程序