Django:模型中的列表字段? [英] Django: List field in model?
问题描述
在我的模型中,我想要一个具有三元组列表的字段。例如[[1,3,4],[4,2,6],[8,12,3],[3,3,9]]。有没有可以将数据存储在数据库中的字段?
可以使用JSON将其转换为字符串并存储作为字符串。
例如,
在[3]中: json.dumps([[1,3,4],[4,2,6],[8,12,3],[3,3,9]])
p $ p>
Out [3] :'[[1,3,4],[4,2,6],[8,12,3],[3,3,9]]'
您可以在课程中添加一个方法,为您自动进行转换。
import json
class Foobar(models.Model):
foo = models.CharField(max_length = 200)
def setfoo(self,x):
self.foo = json.dumps(x)
def getfoo (self):
return json.loads(self.foo)
如果你是使用Django 1.9和postgresql,有一个叫做JSONField的新类,你应该使用它。 这里是一个链接
有关于 youtube
的PostgreSQL JSON和数组,一>。看,它有非常好的信息。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?
解决方案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 setfoo(self, x): self.foo = json.dumps(x) def getfoo(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.
这篇关于Django:模型中的列表字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!