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

查看:854
本文介绍了是否可以在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中,然后,当我需要搜索某些内容时,将值(通过过滤其他模型获得)连接到'[',']'和',',然后使用a具有该生成的字符串的对象过滤器.问题在于,我将必须生成每种可能的组合,然后逐个过滤,直到获得匹配项,并且我认为这样做可能效率不高.

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 one by one until I get a match and I believe that this might be inefficient.

所以,我希望您能给我另一个可以尝试的想法.

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

我不一定要问代码,关于如何实现这一点的任何想法都会很好.

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

推荐答案

我会为您提供两个建议:

I'd have two advices for you:

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天全站免登陆