是否可以在 Django 模型中存储数组? [英] Is it possible to store an array in Django model?

查看:41
本文介绍了是否可以在 Django 模型中存储数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在 Django 模型中存储数组?

I was wondering if it's possible to store an array in a Django model?

我之所以这么问是因为我需要在一个字段中存储一个 int 数组(例如 [1,2,3]),然后才能搜索特定数组并获得匹配项与它或由它可能的组合.

I'm asking this because I need to store an array of int (e.g [1,2,3]) in a field and then be able to search a specific array and get a match with it or by it's possible combinations.

我想将该数组作为字符串存储在 CharFields 中,然后,当我需要搜索某些内容时,将值(通过过滤其他模型获得)与 '[', ']' 连接起来和 ',' 然后对生成的字符串使用对象过滤器.问题是我必须生成每个可能的组合,然后将它们一个一个地过滤,直到匹配为止,我认为这可能效率低下.

I was thinking to store that arrays as strings in CharFields and then, when I need to search something, concatenate the values(obtained by filtering other model) with '[', ']' and ',' and then use a object filter with that generated string. The problem is that I will have to generate each possible combination and then filter them one by one until I get a match, and I believe that this might be inefficient.

所以,我希望你能给我一些我可以尝试的其他想法.

So, I hope you can give me other ideas that I could try.

我不是在要求代码,当然,任何关于如何实现这一目标的想法都会很好.

I'm not asking for code, necessarily, any ideas on how to achieve this will be good.

推荐答案

我有两个建议给你:

1) 如果您使用 PostgreSQL 作为数据库,请使用 ArrayField.您可以在 此处阅读有关 ArrayField 的更多信息.

1) Use ArrayField if you are using PostgreSQL as your database. You can read more about ArrayField here.

2) 将数组编码为 JSON 并将其存储为纯字符串或使用 JSONField 找到的 这里.

2) Encode your array as JSON and store it either as a plain string or using a JSONField as found here.

我个人更喜欢选项 1,因为这是更干净、更好的方式,但取决于您实际使用什么来存储您可能无法使用的数据.

I'd personally prefer option number 1 since that is the cleaner and nicer way but depending on what you are actually using to store your data that might not be available to you.

这篇关于是否可以在 Django 模型中存储数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆