Django: List field in model?

后端 未结 9 1588
感动是毒
感动是毒 2020-11-29 18:38

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 da

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 19:38

    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 and 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.

提交回复
热议问题