gpt4 book ai didi

python-3.x - 将可变长度数组写入数据库

转载 作者:行者123 更新时间:2023-11-29 14:16:02 26 4
gpt4 key购买 nike

我处理一个文章列表,每一个都包含可变数量的标签。如果我不知道以后的更新会有多少标签,如何将标签列表存储为列中的数组?第一次我可以通过用 None 填充它们来插入具有相同长度的标签列表,但是如果有了新的更新我会得到更长的标签列表怎么办?

今天的标签列表:

[tag1, tag2]
[tag1, tag2, tag3]

好的,知道了!最大长度为 3,使长度相等:

[tag1, tag2, None]
[tag1, tag2, tag3]

明天的标签列表:

[tag1, tag2]
[tag1, tag2, tag3]
[tag1, tag2, tag3, tag4]

好的,知道了!我的最大长度是 3:

[tag1, tag2, None]
[tag1, tag2, tag3]
[tag1, tag2, tag3, tag4] <- here is problem

也许有人知道这种情况的更好解决方案?

更新:

for tags in tags_list:
cursor.execute("""INSERT INTO tags VALUES (%s)""", (tags,))

最佳答案

您的印象似乎是数组在 Postgres 中具有固定长度 - 但实际上并非如此:

create table antosha (article_id integer primary key, tags text[]);
insert into antosha (article_id, tags)
values
(1, array['sql', 'dbms']),
(2, array['java', 'jdbc']);

如果你想添加标签,只需附加它们:

-- append a single tag
update antosha
set tags = tags || 'postgresql'
where id = 1;

-- append multiple tags
update antosha
set tags = tags || array['kotlin', 'python']
where id = 2;

或者完全替换标签:

update antosha
set tags = array['one', 'two', 'three', 'four', 'five', 'six']
where id = 1;

或者删除单个元素:

update antosha
set tags = array_remove(tags, 'two')
where id = 1;

或者替换单个元素:

update antosha
set tags = array_replace(tags, 'one', '001')
where id = 1;

关于python-3.x - 将可变长度数组写入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47795634/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com