如何存储动态可变数量对象的顺序(在python中)?

2024-03-29 09:09:58 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我想问a Usera Question“把下列动物从大到小排序”。这里有一点简化的django:

class Question(models.Model):
    text = models.CharField()         #eg "Order the following animals..."

class Image(models.Model):
    image = models.ImageField()       #pictures of animals
    fk_question = models.ForeignKey(Question)

现在,我可以为每个Image分配一个可变数量的Question,并自定义问题文本。耶。你知道吗

记录回答的适当方式是什么?显然,我需要UserQuestion的外键:

class Response(models.Model):
    fk_user = models.ForeignKey(User)
    fk_question = models.ForeignKey(Question)

但现在我被困住了。如何优雅地记录这个User指定的Image对象的顺序?你知道吗

编辑:我用的是Postgres9.5


Tags: djangoimagemodel排序models记录classquestion
1条回答
网友
1楼 · 发布于 2024-03-29 09:09:58

我通常强烈反对在列中存储逗号分隔的数据。然而,这似乎是一个例外的规则!我可以提议CommaSeparatedIntegerField吗?你知道吗

class CommaSeparatedIntegerField(max_length=None, **options)[source]¶
A field of integers separated by commas. As in CharField, the max_length argument is required and the note about database portability mentioned there should be heeded.

这本质上是一个charfield,因此您输入的顺序将保留在db中。你知道吗

你还没提到你的数据库。如果您有幸使用Postgresql和django1.9,那么您也可以使用ArrayField。你知道吗

使用arrayfield会更好,因为这样字符串和列表之间的转换就不存在了。使用逗号分隔字段的情况是,搜索很困难,而且不容易提取第n个元素。POstgresql数组消除了后者的困难。你知道吗

相关问题 更多 >