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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4294039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:06:56  来源:igfitidea点击:

How can I store an array of strings in a Django model?

pythondjangodjango-models

提问by Andrew

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.

谢谢您的帮助。

采纳答案by Ignacio Vazquez-Abrams

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

制作另一个模型,其中包含一个带有可选顺序的字符串,将其ForeignKey返回到myClass,并将您的数组存储在那里。

回答by zoldar

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.

有了这样的字段,您可以无缝地将字符串放入列表并将它们分配给这样的字段。字段抽象将完成剩下的工作。读书也是一样。

回答by FallenAngel

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)

回答by Kaustubh Pandey

If you are using PostgreSQL or MongoDB(with djongo) you can do this

如果您使用的是 PostgreSQL 或 MongoDB(使用 djongo),您可以这样做

For PostgreSQL:

对于 PostgreSQL:

from django.contrib.postgres.fields import ArrayField

For MongoDB(with Djongo):

对于 MongoDB(使用 Djongo):

from djongo import models
from django.contrib.postgres.fields import ArrayField

Then

然后

stringArr = ArrayField(models.CharField(max_length=10, blank=True),size=8)

The above works in both cases.

以上在这两种情况下都有效。

回答by funnydman

You can use JSONFieldfor such functionality:

您可以使用JSONField此类功能:

from django.db import models
from django.contrib.postgres.fields import JSONField

class TestModel(models.Model):
    title = models.CharField(max_length=100)
    strings = JSONField(default=list, blank=True, null=True)

    def __str__(self):
        return self.title

for example:

例如:

In [1]: fruits = ['banana', 'apple', 'orange']                                                                                                                                         

In [2]: TestModel.objects.create(title='my set', strings=fruits)                                                                                                                       
Out[2]: <TestModel: my set>

In [3]: o = TestModel.objects.first()                                                                                                                                                  

In [4]: o.strings                                                                                                                                                                      
Out[4]: ['banana', 'apple', 'orange']

回答by el-Joft

I did this for my model and it worked

我为我的模型做了这个并且它起作用了

from django.contrib.postgres.fields import ArrayField
from django.db import models


class Skill(models.Model):
    name = models.CharField(max_length=50)
    skills = ArrayField(models.CharField(max_length=200), blank=True)

To create

创造

Skill.objects.create(name='First name', skills=['thoughts', 'django'])

To Query

查询

Skill.objects.filter(skills__contains=['thoughts'])

You can refer to the django documentation for more help

更多帮助可以参考django文档

https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/

https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/

I hope this helps

我希望这有帮助