35

I am building a Django data model and I want to be able to store an array of strings in one of the variables; how can I do that?

e.g.

class myClass(models.Model):
    title = models.CharField(max_length=50)
    stringArr = models.???

Thanks for the help.

6 Answers 6

15

If you are using PostgreSQL or MongoDB(with djongo) you can do this

For PostgreSQL:

from django.contrib.postgres.fields import ArrayField

For MongoDB(with Djongo):

from djongo import models
from django.contrib.postgres.fields import ArrayField

Then

stringArr = ArrayField(models.CharField(max_length=10, blank=True),size=8)

The above works in both cases.

Sign up to request clarification or add additional context in comments.

3 Comments

hi working with mongodb using same as you said but whne i do an update i am getting SQLDecodeError at /admin/dataIngestionAPI/submissionfields/1/change/ FAILED SQL: UPDATE "dataIngestionAPI_submissionfields" SET .... can you please help
This is postgresSQL specific model field, you cannot use it with mongodb
It works well if you are using the Djongo driver. Notice the models import is from djongo and not Django. Djongo allows easy switching between different types of database with minimal changes in models
14

You can use some serialization mechanism like JSON. There's a snippet with field definition that could be of some use to you:

http://djangosnippets.org/snippets/1478/ (take a look at the code in the last comment)

With such field you can seamlessly put strings into a list and assign them to such field. The field abstraction will do the rest. The same with reading.

1 Comment

I often use JSON serialized data: be aware though that it is an SQL Antipattern pragprog.com/titles/bksqla/sql-antipatterns, although there are some legitimate uses.
13

Make another model that holds a string with an optional order, give it a ForeignKey back to myClass, and store your array in there.

2 Comments

Isn't that rather inefficient?
If you never have to care what the strings are, sure. As soon as you care, you're going to want more structure.
7

I did this for my model and it worked

from django.contrib.postgres.fields import ArrayField
from django.db import models


class Skill(models.Model):
    name = models.CharField(max_length=50)
    skills = ArrayField(models.CharField(max_length=200), blank=True)

To create

Skill.objects.create(name='First name', skills=['thoughts', 'django'])

To Query

Skill.objects.filter(skills__contains=['thoughts'])

You can refer to the django documentation for more help

https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/

I hope this helps

Comments

4

You can use cPickle...

class myClass(models.Model):
    title = models.CharField(max_length=50)
    stringArr = models.TextField()

from cPickle import loads, dumps
data = [ { 'a':'A', 'b':2, 'c':3.0 } ]
obj = Myclass.objects.get(pk=???)
# pickle data into a string-like format
obj.stringArr = dumps(data)
obj.save()
# restore original data
data = loads(obj.stringArr)

1 Comment

You can also generalise this to a PickleField, or use the one on pypi: pypi.python.org/pypi/django-picklefield
4

You can use JSONField for such functionality:

from django.db import models
from django.contrib.postgres.fields import JSONField

class TestModel(models.Model):
    title = models.CharField(max_length=100)
    strings = JSONField(default=list, blank=True, null=True)

    def __str__(self):
        return self.title

for example:

In [1]: fruits = ['banana', 'apple', 'orange']                                                                                                                                         

In [2]: TestModel.objects.create(title='my set', strings=fruits)                                                                                                                       
Out[2]: <TestModel: my set>

In [3]: o = TestModel.objects.first()                                                                                                                                                  

In [4]: o.strings                                                                                                                                                                      
Out[4]: ['banana', 'apple', 'orange']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.