【问题标题】:How to make upper bound inclusive using SQLAlchemy + Postgres如何使用 SQLAlchemy + Postgres 使上限包含在内
【发布时间】:2020-11-16 11:12:43
【问题描述】:

我的专栏是这样的:

Class School(db.model):
    year = db.Column(INT4RANGE, nullable=False) 

当我提交时:

y = NumericRange(2020,2021,'[]')
school = School(year=y)
db.session.add(school)
db.session.commit()

但是当我查询它显示的列时:

[2020,2021)

为什么会这样?为了过滤,我需要它包含下限和上限。

【问题讨论】:

  • 这似乎是 SQLAlchemy 中的一个错误,int4range(2020,2021, '[]') 在“plain Postgres”中导致[2020,2022) dbfiddle.uk/…
  • 如果这确实是 SQLAlchemy 中的一个错误,请报告它on GitHub
  • NumericRange 实际上来自 psycopg2。
  • @a_horse_with_no_name。同一事物的不同表示:select int4range(2020,2021, '[]') = '[2020,2021]'::int4range; ?column? ---------- t
  • 但是2020,2021,'[]'2020,2021,'[)' 不同。似乎 Python 的 NumericRange(2020,2021,'[]') 做了一些不同于 int4range(2020,2021, '[]'

标签: postgresql sqlalchemy range psycopg2


【解决方案1】:

我没有安装 SQLAlchemy,但这是我看到的:

create table integer_range(range_field int4range);
insert into integer_range values (int4range(2020, 2021, '[]'));
insert into integer_range values (int4range(2020, 2021, '[)'));
insert into integer_range values (int4range(2019, 2020, '[)'));

在 Python 中:

import psycopg2
from psycopg2.extras import NumericRange
con = psycopg2.connect("dbname=test user=aklaver host=localhost port=5442") 
cur = con.cursor() 
cur.mogrify("select * from integer_range where range_field = %s", (NumericRange(2020,2021,'[]'),))                                                                                                                      
b"select * from integer_range where range_field = '[2020,2021]'"
cur.execute("select * from integer_range where range_field = %s", (NumericRange(2020,2021,'[]'),)) 
rs = cur.fetchall() 
rs[0]                                                                                                                                                                                                                   
(NumericRange(2020, 2022, '[)'),)

所以它在 psycopg2 ene 中有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 2018-09-02
    • 2021-05-25
    相关资源
    最近更新 更多