Can an array be stored in a Django model?
I was wondering if it is possible to store an array in a Django model?
I ask this because I need to store an array of int (eg [1,2,3]) in a field, and then be able to search for a specific array and get a match against it or possible combinations of it.
I thought of storing these arrays as strings in charfields, and then when I need to search for something, concatenate the values (obtained by filtering another model) with "[','] 'and', 'and then use the object filter with with this generated string The problem is that I will have to create every possible combination and then filter one by one until there is a match, and I think that might not be efficient.
So, I hope you can give me other ideas that I could try.
I don't necessarily require any code, any ideas on how to achieve this would be good.
source to share
I have two tips for you:
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 JSONField
either as a simple string or using JSONField
like JSONField
here .
I personally would prefer option # 1 as it is a cleaner and nicer way, but depending on what you actually use to store your data, that might not be available to you.
source to share