Skip to main content
 首页 » 编程设计

python之Django unique_together 不起作用 : "refers to the non-existent field"

2024年08月23日34Leo_wl

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

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

请您参考如下方法:

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

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

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

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

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

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