如何在Django模型中存储字符串数组?

时间:2021-05-31 19:39:47

I am building a Django data model and I want to be able to store an array of strings in one of the variables; how can I do that?

我正在构建一个Django数据模型,我希望能够在其中一个变量中存储一个字符串数组;我怎样才能做到这一点?

e.g.

例如

class myClass(models.Model):
    title = models.CharField(max_length=50)
    stringArr = models.???

Thanks for the help.

谢谢您的帮助。

3 个解决方案

#1


7  

Make another model that holds a string with an optional order, give it a ForeignKey back to myClass, and store your array in there.

创建另一个包含带有可选顺序的字符串的模型,将一个ForeignKey返回给myClass,并将数组存储在那里。

#2


9  

You can use some serialization mechanism like JSON. There's a snippet with field definition that could be of some use to you:

您可以使用一些序列化机制,如JSON。有一个字段定义的片段可能对你有用:

http://djangosnippets.org/snippets/1478/ (take a look at the code in the last comment)

http://djangosnippets.org/snippets/1478/(看看上一条评论中的代码)

With such field you can seamlessly put strings into a list and assign them to such field. The field abstraction will do the rest. The same with reading.

使用此类字段,您可以将字符串无缝地放入列表并将其分配给此类字段。字段抽象将完成其余的工作。与阅读相同。

#3


4  

You can use cPickle...

你可以用cPickle ......

class myClass(models.Model):
    title = models.CharField(max_length=50)
    stringArr = models.TextField()

from cPickle import loads, dumps
data = [ { 'a':'A', 'b':2, 'c':3.0 } ]
obj = Myclass.objects.get(pk=???)
# pickle data into a string-like format
obj.stringArr = dumps(data)
obj.save()
# restore original data
data = loads(obj.stringArr)

#1


7  

Make another model that holds a string with an optional order, give it a ForeignKey back to myClass, and store your array in there.

创建另一个包含带有可选顺序的字符串的模型,将一个ForeignKey返回给myClass,并将数组存储在那里。

#2


9  

You can use some serialization mechanism like JSON. There's a snippet with field definition that could be of some use to you:

您可以使用一些序列化机制,如JSON。有一个字段定义的片段可能对你有用:

http://djangosnippets.org/snippets/1478/ (take a look at the code in the last comment)

http://djangosnippets.org/snippets/1478/(看看上一条评论中的代码)

With such field you can seamlessly put strings into a list and assign them to such field. The field abstraction will do the rest. The same with reading.

使用此类字段,您可以将字符串无缝地放入列表并将其分配给此类字段。字段抽象将完成其余的工作。与阅读相同。

#3


4  

You can use cPickle...

你可以用cPickle ......

class myClass(models.Model):
    title = models.CharField(max_length=50)
    stringArr = models.TextField()

from cPickle import loads, dumps
data = [ { 'a':'A', 'b':2, 'c':3.0 } ]
obj = Myclass.objects.get(pk=???)
# pickle data into a string-like format
obj.stringArr = dumps(data)
obj.save()
# restore original data
data = loads(obj.stringArr)