In my models.py, I have the following code:
from __future__ import unicode_literals
from django.db import models
from django.contrib.postgres.fields import JSONField
import json
class Table(models.Model):
name = models.CharField(max_length=255)
structure = JSONField(default=json.dumps('{}'))
def __unicode__(self):
return self.name
class Column(models.Model):
table = models.ForeignKey(Table, related_name='columns')
name = models.CharField(max_length=255)
required = models.BooleanField(default=True)
def __unicode__(self):
return self.name + ' FROM TABLE ' + self.table.name
def save(self, *args, **kwargs):
if not self.pk:
self.table.structure[self.name] = {
'required' : self.required,
}
As you can see from the code, when a Column is saved, if the column's required field gets added to the structure of the Table. However, when I try saving a column from the admin panel, I get the following error:
TypeError at /admin/myapp/column/add/
'unicode' object does not support item assignment
I think the problem is with the default value of my structure field. I also tried the following:
structure = JSONField(default={})
structure = JSONField(default='{}')
structure = JSONField(default=dict)
Each time, I got the same error. Any help? Thanks.