Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use postgres numeric range with SQLAlchemy

I can't happen to find much on using Postgres range types in SQLAlchemy other than this. Does anyone know how to insert new column values into a numrange column? Does anyone have some code snippets or more documentation than the one I already found?

like image 834
orange Avatar asked May 09 '14 11:05

orange


People also ask

Can SQLAlchemy be used with PostgreSQL?

This SQLAlchemy engine is a global object which can be created and configured once and use the same engine object multiple times for different operations. The first step in establishing a connection with the PostgreSQL database is creating an engine object using the create_engine() function of SQLAlchemy.

What is DB Create_all ()?

Sqlalchemy create_all method is used to create a new table into the database. This method will first check whether the table exists in the database or not if suppose it has found an existing table it will not create any table.

What is enum in SQLAlchemy?

Enum is a class within the sqlalchemy. types module of the SQLAlchemy project.


1 Answers

This has been added to the official documentation: https://bitbucket.org/zzzeek/sqlalchemy/issue/3046/postgresql-range-types-need-better


Had to dig around for this, but when in doubt, check the tests! The SQLAlchemy tests for the range types use the underlying 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()
like image 191
davidism Avatar answered Jan 01 '23 23:01

davidism