[Fixed]-Model Array in Django

1👍

I’m trying to model something like: “Field”:[ { “opt1”:val1, “opt2”:val2}, { “opt1”:val1, “opt2”:val2}].

Django models are wrapper over a relational database. Relational database don’t have multivalued fields, they use relationships instead – in this case a one to many relationship. IOW, you need another model for your options with a ForeignKey on your model ie:

class Test(models.Model):
    name = models.TextField(required=True)

class Option(models.Model):
    test = models.ForeignKey(Test, related_name="options")
    opt1 = models.CharField(...)
    opt2 = models.CharField(...)

Then you can access your options thru test.options.XXX, ie:

t = Test.objects.create(name="test")
# list existing options
print t.options.all() 
# add an option
t.options.create(opt1="foo", opt2="bar") 

More documentation here and here….

You can also use a some of the available JSONField implementations, but you’ll loose quite a few things on the way (querying on options values – unless using PostgreSQL -, db and model level constraints etc, automagic admin and models forms etc).

0👍

first install jsonfield by using

pip install jsonfield 

then

from jsonfield import JSONField    
data = JSONField(blank=True, null=True)

Leave a comment