[英]How do I access the last index of an ArrayField in a peewee query with postgres?
I have a model with an Array field, and I'd like to find records where the last element of the field is greater than a known value.我有一个带有 Array 字段的模型,我想查找该字段的最后一个元素大于已知值的记录。 The array field will hold arrays of varying length.数组字段将保存不同长度的数组。
I thought that using something like Test.select().where(known_value <= Test.array_field[-1])
for model {Test} would work, but that {-1} doesn't seem to work as expected.我认为对模型 {Test} 使用类似Test.select().where(known_value <= Test.array_field[-1])
的东西会起作用,但是 {-1} 似乎没有按预期工作。 Here's a minimum working example:这是一个最低限度的工作示例:
from os import path, environ
import peewee as pw
from playhouse.postgres_ext import ArrayField
from db_stuff import connect, get_database
class Test(pw.Model):
# note an 'id' primary key field will be created by peewee by default
value = ArrayField(pw.IntegerField)
class Meta:
table_name = 'test2'
# connects the model to the database and returns the instance, details are
# unimportant
connect('test_db_login.json', [Test])
database = get_database()
database.create_tables([Test])
Test.create(value=[1,2,3,4])
Test.create(value=[5,6,7,8])
known_value = 6
for entry in Test.select():
# outputs both records
print('id', entry.id, 'value', entry.value)
for entry in Test.select().where(Test.value[0] <= known_value):
# outputs both records
print('id', entry.id, 'value', entry.value, 'first value', entry.value[0])
for entry in Test.select().where(known_value <= Test.value[-1]):
# outputs nothing
print('id', entry.id, 'value', entry.value, 'last value', entry.value[-1])
When I try a raw sql query on the table, things work as expected: SELECT "t1"."id", "t1"."value" FROM "test2" AS "t1" WHERE ("t1"."value"[ARRAY_UPPER("t1"."value", 1)] >= 6);
当我在表上尝试原始 sql 查询时,事情按预期工作: SELECT "t1"."id", "t1"."value" FROM "test2" AS "t1" WHERE ("t1"."value"[ARRAY_UPPER("t1"."value", 1)] >= 6);
, returning the second record. ,返回第二条记录。
I looked around a bunch in the peewee code and searched around online for a mechanism with functionality like ARRAY_UPPER
in peewee, but had no luck.我环顾了 peewee 代码中的一堆,并在网上搜索了一种具有像ARRAY_UPPER
中的 ARRAY_UPPER 之类的功能的机制,但没有运气。
Any recommendations here?这里有什么建议吗?
You should probably index using an expression like fn.array_upper(Test.value, 1)
as you indicated.您应该按照您的指示使用像fn.array_upper(Test.value, 1)
这样的表达式进行索引。
Fixed by 55ef182840f869f63 in master, will be available in the next release.由 master 中的 55ef182840f869f63 修复,将在下一个版本中可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.