如何在 Tortoise-ORM 中使用 Postgresql 数组字段

Jak*_*ski 5 python postgresql asyncpg tortoise-orm

几乎如标题所示,我正在尝试设置 Tortoise-ORM 模型,其中包含与 Postgresql 数组列相对应的字段。

似乎要正确地做到这一点,我需要从 asyncpg (因为它具有完整的数组支持)向上扩展 Tortoise Field 进行构建。然而,我刚刚开始使用乌龟,也许有一些更好/更简单的方法/有人已经做了类似的事情。

and*_*nik 3

您需要实现自己的字段类型。这是我的实现:


from typing import List, Union, Type, Optional, Any
import json

from tortoise.fields.base import Field
from tortoise.models import Model


class IntArrayField(Field, list):
    """
    Int Array field specifically for PostgreSQL.

    This field can store list of int values.
    """

    SQL_TYPE = "int[]"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def to_db_value(
        self, value: List[int], instance: "Union[Type[Model], Model]"
    ) -> Optional[List[int]]:
        return value

    def to_python_value(self, value: Any) -> Optional[List[int]]:
        if isinstance(value, str):
            array = json.loads(value.replace("'", '"'))
            return [int(x) for x in array]
        return value
Run Code Online (Sandbox Code Playgroud)

我没有动态类型字段实现,这并不难实现。

to_db_value在某些情况下,您需要在转换中加入更多逻辑to_python_value。例如,如果您正在使用UUID[].