【问题标题】:django : arrayfield with custom model as base fielddjango:以自定义模型为基础字段的数组字段
【发布时间】:2020-09-09 19:13:39
【问题描述】:

我有自定义模型

class customModel(models.Model):
    contents = models.TextField(null=True)

还有另一个带有 ArrayField 的 customModel

from django.contrib.postgres.fields import ArrayField
class customModel2(models.Model):
    ArrayField(customModel()):

但它引发了错误 AttributeError: 'customModel' 对象没有属性 'set_attributes_from_name'

ArrayField(customModel) also raised similar errors.

使用自定义模型作为基本字段定义数组字段的正确方法是什么?

【问题讨论】:

    标签: python django


    【解决方案1】:

    错误表明您没有设置名称属性。这样做

    from django.db import models
    class CustomModel2(models.Model):
        # making an array of foreign keys of customModel
        # you can also use models.Integer etc
        myArray = ArrayField(
                models.ForeignKey(customModel, on_delete=models.CASCADE),
                size=8,
            )
    
    

    【讨论】:

    • 另外,这可能会有所帮助,因为您使用的是 arrayField stackoverflow.com/a/51893414/11979793
    • 不可能使用 ForeignKey 作为 ArrayField 的基本字段,请参阅stackoverflow.com/questions/35957837/…
    • @Idocao 限制是 Postgres,而不是 Django。它可以在其他领域实施。该问题没有提到 Postgres 的使用。或者,我在第一条评论中提供了 manytomany 字段解决方案。
    猜你喜欢
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 2015-04-16
    • 2022-01-24
    • 2017-10-21
    相关资源
    最近更新 更多