Search code examples
djangodjango-orm

List field in model?


In my model, I want a field that has a list of triplets. e.g. [[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]]. Is there a field that can store this data in the database?


Solution

  • You can convert it into string by using JSON and store it as string.

    For example,

    In [3]: json.dumps([[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]])
    
    Out[3]: '[[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]]'
    

    You can add a method into your class to convert it automatically for you.

    import json
    
    
    class Foobar(models.Model):
        foo = models.CharField(max_length=200)
    
        def set_foo(self, x):
            self.foo = json.dumps(x)
    
        def get_foo(self):
            return json.loads(self.foo)
    

    If you're using Django 1.9 or above, and you use postgresql, there is a new class called JSONField, you should use it instead. Here is a link to it

    There is a good talk about PostgreSQL JSONs and Arrays on youtube. Watch it, it has very good information.