gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:58:45 24 4
gpt4 key购买 nike

在 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 syncdbSystemCheckError:系统检查发现了一些问题:

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

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

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

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

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

关于python - Django unique_together 不起作用 : "refers to the non-existent field",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33831221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com