Reputation: 3999
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.
Upvotes: 35
Views: 39644
Reputation: 159
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.
Upvotes: 15
Reputation: 160
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
Upvotes: 7
Reputation: 11326
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']
Upvotes: 4
Reputation: 18727
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)
Upvotes: 4
Reputation: 231
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.
Upvotes: 14
Reputation: 798516
Make another model that holds a string with an optional order, give it a ForeignKey
back to myClass
, and store your array in there.
Upvotes: 13