简体   繁体   English

如何在 POSTGRESQL FlaskSQLAlchemy 中将列定义为任何类型的数组?

[英]How to define a column as an Array of any type in POSTGRESQL FlaskSQLAlchemy?

I am using flask_sqlalchemy and I want to define column prompts to be an array which accepts values of any data type, particularly string or json .我正在使用flask_sqlalchemy并且我想将列提示定义为一个数组,它接受任何数据类型的值,特别是stringjson

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)

class PreannotationPrompts(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique = True)
    type = db.Column(db.String(100))
    '''
    Example of values prompts should hold
    [
         {"key": "value", "key2": []},
         'Hello',
         {"key": "value", "key2": []},
         'Hi'
    ]
    '''
    prompts = db.Column(db.String(1000))  # How to define ? 

How can I define prompts column appropriately in this case?在这种情况下如何适当地定义提示列?

SQL is a typed language, you you cannot have a column that accepts "any type". SQL 是一种类型化语言,您不能拥有接受“任何类型”的列。 You should rethink your data model.您应该重新考虑您的数据模型。 Avoid arrays as column data types.避免将数组作为列数据类型。

If you anticipate fluid model within a column you probably should use JSONB type.如果您预计列中有流体模型,您可能应该使用 JSONB 类型。 You can store a dict or an array without a priori declared element's type.您可以在没有先验声明元素类型的情况下存储字典或数组。

from sqlalchemy.dialects.postgresql import JSONB

prompts = db.Column(JSONB, default=list) 

However, using a schemaless column (like JSONB) can indicate that you have a problem with properly designed data model.但是,使用无模式列(如 JSONB)可能表明您在正确设计的数据模型方面存在问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何定义具有不同列值类型的一个矩阵或二维数组,并在Python中有效地检索列 - How to define one matrix or two-dimensional array with different column value type and retrieve the column efficiently in Python 是否有任何优雅的方法来定义具有dtype数组列的数据框? - Is there any elegant way to define a dataframe with column of dtype array? 如何根据PostgreSQL中的列值定义唯一约束? - how to define a unique constraint depending on column value in postgresql? 如何将自定义类型数组传递给 PostgreSQL 函数 - How to pass an array of customs type to a PostgreSQL function 如何在PostgreSQL REAL类型列中插入python NUMERIC类型 - How to insert a python NUMERIC type in postgresql REAL type column 使用SQLAlchemy定义PostgreSQL字符串列的最小长度 - Define minimum length for PostgreSQL string column with SQLAlchemy 如何为具有任意数量的 Any 类型关键字参数的 Callable 类型定义 Python 协议? - How do I define a Python Protocol for a type that is Callable with any number of keyword arguments of Any type? 如何动态创建order_by语句并将其注入flask.alchemy查询 - How to dynamically create order_by statements and inject them into flasksqlalchemy query 在Pandas中将列类型定义为“列表” - Define a column type as 'list' in Pandas 熊猫:定义新列的类型 - Pandas: Define type of new column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM