[英]How to use Postgresql Array field in Tortoise-ORM
Pretty much the title, I'm trying to setup Tortoise-ORM model that will include Field corresponding to Postgresql Array column.几乎是标题,我正在尝试设置 Tortoise-ORM model ,其中将包含对应于 Postgresql 数组列的字段。
It seems like to do it properly I'd need to build from asyncpg (since it has full array support) up extending Tortoise Field.似乎要正确地做到这一点,我需要从 asyncpg 构建(因为它具有完整的数组支持)向上扩展 Tortoise Field。 However I'm just starting with Tortoise and maybe there's some better/easier way forward/someone already did something similar.
但是,我刚刚从乌龟开始,也许有一些更好/更简单的前进方式/有人已经做了类似的事情。
You need to implement your own field type.您需要实现自己的字段类型。 Here is my implementation:
这是我的实现:
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
I don't have dynamic type field implementation, which is not so difficult to make from this.我没有动态类型字段实现,这并不难。
In some cases you need to put more logic into to_db_value
and to_python_value
casting.在某些情况下,您需要将更多逻辑放入
to_db_value
和to_python_value
转换中。 For instance, if you are using UUID[]
.例如,如果您使用
UUID[]
。
You can now use ArrayField from the contrib part of tortoise ( >= 0.19
).您现在可以使用来自 tortoise (
>= 0.19
) 的 contrib 部分的 ArrayField。
from tortoise.contrib.postgres.fields import ArrayField
int_array = ArrayField()
text_array = ArrayField(element_type="text")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.