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.

+7


source to share


3 answers


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.

+15


source


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.

+5


source


If you are not using Postgres I recommend the Django validate_comma_separated_integer_list

validator.

https://docs.djangoproject.com/en/dev/ref/validators/#django.core.validators.validate_comma_separated_integer_list

You use it as a validator for CharField()

.

+1


source







All Articles