'How can I store an array of strings in a Django model?
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.
Solution 1:[1]
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.
Solution 2:[2]
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.
Solution 3:[3]
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)
Solution 4:[4]
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
Solution 5:[5]
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']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | zoldar |
| Solution 2 | |
| Solution 3 | FallenAngel |
| Solution 4 | el-Joft |
| Solution 5 | funnydman |
