Python Django unique“一起工作不起作用:”;指不存在的字段;

Python Django unique“一起工作不起作用:”;指不存在的字段;,python,django,models,Python,Django,Models,在Django中创建模型时,我需要使两个整数字段的组合唯一: class example(models.Model): lenght = models.PositiveSmallIntegerField position = models.PositiveSmallIntegerField otherfield = models.ForeignKey('onetable') otherfield2 = models.ForeignKey('anothertable

在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"),)
因此,当我同步数据库时,会收到以下错误消息:

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"),)
正在执行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"),)

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

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

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

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

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