可以在Django模型中存储数组吗?

时间:2022-02-04 07:24:52

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

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

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.

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

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.

我不是必须要求代码,任何关于如何实现这一点的想法都会很好。

2 个解决方案

#1


9  

I'd have two advices for you:

我有两个建议给你:

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

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

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

2)将您的数组编码为JSON,并将其存储为纯字符串或使用此处的JSONField。

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.

我个人更喜欢第1号选项,因为这是更清洁,更好的方式,但取决于您实际用于存储可能无法使用的数据的内容。

#2


4  

Yes, you can use it like this:

是的,您可以像这样使用它:

from django.contrib.postgres.fields import ArrayField
class Board(models.Model):
    pieces = ArrayField(ArrayField(models.IntegerField()))

However, it can only be available when using PostgreSQL for the database.

但是,它只能在将PostgreSQL用于数据库时才可用。

#1


9  

I'd have two advices for you:

我有两个建议给你:

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

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

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

2)将您的数组编码为JSON,并将其存储为纯字符串或使用此处的JSONField。

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.

我个人更喜欢第1号选项,因为这是更清洁,更好的方式,但取决于您实际用于存储可能无法使用的数据的内容。

#2


4  

Yes, you can use it like this:

是的,您可以像这样使用它:

from django.contrib.postgres.fields import ArrayField
class Board(models.Model):
    pieces = ArrayField(ArrayField(models.IntegerField()))

However, it can only be available when using PostgreSQL for the database.

但是,它只能在将PostgreSQL用于数据库时才可用。