数组数据类型支持

概述

从 Pony 0.7.7 版本开始,我们为 PostgreSQL、CockroachDB 和 SQLite 添加了对数组类型的支持。它实现了 PostgreSQL 的数组。JSON 类型更加灵活,但在某些情况下,数组类型可能更高效。

声明数组属性

每个数组都应该指定一个类型,该类型表示该数组可以存储的项目类型。支持的类型为:intfloatstr

要使用 Pony 声明数组属性,您应该使用 IntArrayFloatArrayStrArray 类型之一。这些类型可以从 pony.orm 包中导入。

from pony.orm import *

db = Database()


class Product(db.Entity):
    id = PrimaryKey(int, auto=True)
    name = Required(str)
    stars = Optional(IntArray)
    tags = Optional(StrArray)


db.bind('sqlite', ':memory:')
db.generate_mapping(create_tables=True)

 with db_session:
     Product(name='Apple MacBook', stars=[0, 2, 0, 5, 10], tags=['Apple', 'Notebook'])

注意

可选数组默认情况下声明为 NOT NULL,并使用空数组作为默认值。要使其可为空,您应该传递 nullable=True 选项。

注意

对于 PostgreSQL,如果您设置 index=True,Pony 将创建 gin 索引。对于 SQLite,索引将被忽略。

数组操作

访问数组项

在 PonyORM 中,数组索引从零开始,与 Python 中一样。可以使用负索引从末尾访问数组。您也可以使用数组切片。

选择数组的特定项

select(p.tags[2] for p in Product)[:]  # third element
select(p.tags[-1] for p in Product)[:]  # last element

使用切片

select(p.tags[:5] for p in Product)[:]  # first five elements

注意

切片不支持步长。

检查数组中是否包含某个项目或项目列表

select(p for p in Product if 'apple' in p.tags)[:]
select(p for p in Product if ['LCD', 'DVD', 'SSD'] in p.tags)[:]

更改数组的项目

product = Product.select().first()
product.tags.remove('factory-new')
product.tags.append('reconstructed')