Currently I have a lot of python objects in my code similar to the following:
class MyClass():
def __init__(self, name, friends):
self.myName = name
In case you're using postgres, you can use something like this:
class ChessBoard(models.Model):
board = ArrayField(
ArrayField(
models.CharField(max_length=10, blank=True),
size=8,
),
size=8,
)
if you need more details you can read in the link below: https://docs.djangoproject.com/pt-br/1.9/ref/contrib/postgres/fields/
My solution, may be it helps someone:
import json
from django.db import models
class ExampleModel(models.Model):
_list = models.TextField(default='[]')
@property
def list(self):
return json.loads(self._list)
@list.setter
def list(self, value):
self._list = json.dumps(self.list + value)
You can store virtually any object using a Django Pickle Field, ala this snippet:
http://www.djangosnippets.org/snippets/513/
A simple way to store a list in Django is to just convert it into a JSON string, and then save that as Text in the model. You can then retrieve the list by converting the (JSON) string back into a python list. Here's how:
The "list" would be stored in your Django model like so:
class MyModel(models.Model):
myList = models.TextField(null=True) # JSON-serialized (text) version of your list
In your view/controller code:
Storing the list in the database:
import simplejson as json # this would be just 'import json' in Python 2.7 and later
...
...
myModel = MyModel()
listIWantToStore = [1,2,3,4,5,'hello']
myModel.myList = json.dumps(listIWantToStore)
myModel.save()
Retrieving the list from the database:
jsonDec = json.decoder.JSONDecoder()
myPythonList = jsonDec.decode(myModel.myList)
Conceptually, here's what's going on:
>>> myList = [1,2,3,4,5,'hello']
>>> import simplejson as json
>>> myJsonList = json.dumps(myList)
>>> myJsonList
'[1, 2, 3, 4, 5, "hello"]'
>>> myJsonList.__class__
<type 'str'>
>>> jsonDec = json.decoder.JSONDecoder()
>>> myPythonList = jsonDec.decode(myJsonList)
>>> myPythonList
[1, 2, 3, 4, 5, u'hello']
>>> myPythonList.__class__
<type 'list'>
Remember that this eventually has to end up in a relational database. So using relations really is the common way to solve this problem. If you absolutely insist on storing a list in the object itself, you could make it for example comma-separated, and store it in a string, and then provide accessor functions that split the string into a list. With that, you will be limited to a maximum number of strings, and you will lose efficient queries.
Would this relationship not be better expressed as a one-to-many foreign key relationship to a Friends
table? I understand that myFriends
are just strings but I would think that a better design would be to create a Friend
model and have MyClass
contain a foreign key realtionship to the resulting table.