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

查看:79
本文介绍了是否可以在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.

我正在考虑将该数组作为字符串存储在 CharField s中,然后,当我需要搜索某些内容时,将值(通过过滤其他模型获得)连接为'[' ,]和,,然后对生成的字符串使用对象过滤器。问题是我必须生成每种可能的组合,然后逐个过滤,直到得到匹配为止,我相信这样做可能效率不高。

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.

推荐答案

我会为您提供两个建议:

I'd have two advices for you:

1)使用 ArrayField (如果使用PostgreSQL作为数据库)。您可以阅读有关 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天全站免登陆