【问题标题】:django nesting TextField within ArrayField for postgresdjango 在 ArrayField 中为 postgres 嵌套 TextField
【发布时间】:2021-06-05 13:41:51
【问题描述】:

Django 提供了一种在 PGSql 中编写 ArrayFields 的好方法:

https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#arrayfield

例如:

class Board(models.Model):
    pieces = ArrayField(ArrayField(models.IntegerField()))

我还看到了使用 CharField 的其他示例 - 我过去曾使用过并且工作正常。

现在,我想知道我是否可以像这样对 TextField 做同样的事情:

class Board(models.Model):
    extra_array = ArrayField(models.TextField(blank=True), default=list)

这样做是否合法?有什么我需要注意的问题吗?这些示例似乎都没有使用 TextField,我想知道为什么!

【问题讨论】:

  • 尝试了吗?文档声明“大多数字段类型都是允许的,但处理关系数据的除外”。你说“这些例子似乎都没有使用TextField”。字段太多了,为每个字段添加一个示例将是多余的...
  • 啊!我刚刚看到Most field types are permitted, with the exception of those handling relational data :( 今天早上失明-我很抱歉。请将其发布为答案,我会接受。

标签: python-3.x django


【解决方案1】:

首先,文档(如您在问题中链接)指出:

大多数字段类型都是允许的,除了那些处理 关系数据(ForeignKeyOneToOneFieldManyToManyField)。

考虑到这一点,应该很确定TextField 会起作用。查看代码thisArrayField 检查它是否有效的地方:

def check(self, **kwargs):
    errors = super().check(**kwargs)
    if self.base_field.remote_field:
        errors.append(
            checks.Error(
                'Base field for array cannot be a related field.',
                obj=self,
                id='postgres.E002'
            )
        )
    else:
        # Remove the field name checks as they are not needed here.
        base_errors = self.base_field.check()

无论如何,这段代码并不表明TextField 不是有效的base_fieldTextField 没有设置remote_field,只要字段自己的声明没问题,else 部分也可以正常工作) .

注意:不确定时试试!一个问题是“做 XYZ 是否合法/可能?” 这不是一个很好的问题。最多你会失败并找到 出 XYZ 不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-07
    • 2016-08-13
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 2017-04-29
    相关资源
    最近更新 更多