【问题标题】:Django unique_together does not work: "refers to the non-existent field"Django unique_together 不起作用:“指的是不存在的字段”
【发布时间】:2015-11-20 16:13:13
【问题描述】:

在Django中创建模型,我需要使两个整数字段的组合唯一:

class example(models.Model):
    lenght = models.PositiveSmallIntegerField
    position = models.PositiveSmallIntegerField
    otherfield = models.ForeignKey('onetable')
    otherfield2 = models.ForeignKey('anothertable')

    class Meta:
        unique_together = (("lenght", "position"),)

所以当我同步数据库时,我会收到以下错误消息:

执行manage.py syncdb SystemCheckError:系统检查发现一些问题:

ERRORS:
prj.CodeBlock: (models.E012) 'unique_together' refers to the non-existent field 'lenght'.
prj.CodeBlock: (models.E012) 'unique_together' refers to the non-existent field 'position'.
The Python REPL process has exited
>>> 

我发现如果我将字段类型更改为“charfield”,我没有收到任何错误消息:

class example(models.Model):
    lenght = models.CharField(max_length=8)
    position = models.CharField(max_length=8)
    otherfield = models.ForeignKey('onetable')
    otherfield2 = models.ForeignKey('anothertable')

    class Meta:
        unique_together = (("lenght", "position"),)

为什么我不能使整数字段的组合唯一?

【问题讨论】:

    标签: python django models


    【解决方案1】:

    因为您没有声明(实例化)整数字段(您只是引用了它们的类):

    class example(models.Model):
        lenght = models.PositiveSmallIntegerField
        position = models.PositiveSmallIntegerField
    

    lengthposition 不是字段实例,而是字段类。尝试将它们实例化为表中实际存在的字段:

    class example(models.Model):
        lenght = models.PositiveSmallIntegerField()
        position = models.PositiveSmallIntegerField()
    

    在其元类中,Django 检测并枚举字段实例(即通过运行isinstance(v, Field))并创建它们的列。您可以在您的类中声明任何值(方法是属性;也许您的类有自定义异常或 choices= 参数的常量值,...),但只会枚举 Field 实例。这适用于字段类:Django 不会对它们进行特殊处理:也许您将自定义 Field 类声明为模型中的内部类(旨在仅在您的模型中使用),并且您不会期望它只是一个字段...这就是为什么 Django 不将字段类的引用转换为字段实例的引用的原因。

    你必须是明确的。也许你忘记了括号。

    【讨论】:

      猜你喜欢
      • 2017-01-14
      • 2014-11-23
      • 2017-08-23
      • 2011-11-23
      • 1970-01-01
      • 1970-01-01
      • 2016-08-17
      • 2016-08-08
      • 2011-05-22
      相关资源
      最近更新 更多