首页 > 解决方案 > 哪种列类型支持 sqlalchemy 中的列表?

问题描述

我目前正在为太阳能活跃区域建立一个数据库,其中一列应该获取区域编号,目前我已通过以下方式声明:

noaa_number = sql.Column(sql.Integer, nullable=True)

但是,由于可能会随着区域的发展而分配新的编号,哪种列类型会更好地支持列表以保留给定区域的所有编号?因此,而不是像这样的条目:

noaa_number = 12443

我可以将我的结果存储为:

#a simple entry
noaa_number = [12443]
#or multiple results
noaa_number = [12444,12445]

列表中的这些元素将是整数。

我正在检查文档,我的最佳想法是将此列作为字符串放置并解析其中的所有数字。虽然这样会很好,但我想知道是否有更好、更合适的方法。

标签: pythonpython-3.xlistsqlalchemy

解决方案


In some cases you can use array column. This is really not bad way to store very specific data. Example:

class Example(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    my_array = db.Column(db.ARRAY(db.Integer())

# You can easily find records:
# Example.my_array.contains([1, 2, 3]).all()
# You can use text items of array
# db.Column(db.ARRAY(db.Text())

Also you can use CompositeArray (sqlalchemy_utils) to use custom database types as array items. Example:

# let's imagine that we have some meta history
history = db.Column(
        CompositeArray(
            CompositeType(
                'history',
                [
                    db.Column('message', db.Text),
                ]
             )
        )
# example of history type:
CREATE TYPE history AS (
   message text
);

Note! Not sure about sqlite but with postgres should works fine.

Hope this helps.


推荐阅读