Search code examples
pythonarraysdjango

Is it possible to store an array in Django model?


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

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.

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.


Solution

  • Two possibilities:

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

    2. Encode your array as JSON and store it either as a plain string or using a JSONField. Django added a cross-platform JSONField in version 3.1. For earlier versions, here is an example library.

    I'd personally prefer option number 1, since that is cleaner but that might not be available to you.