2015-11-20 78 views
2

創建在Django的模型,我需要做出獨特的兩個整型字段的組合:Django的unique_together不起作用:「指的是不存在的領域」

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

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

所以,當我同步數據庫I收到以下錯誤信息:

執行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 
>>> 

我看看I C焊割爲「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"),) 

爲什麼我不能讓唯一的整數字段的組合?

回答

3

因爲你沒有申報(實例)的整數字段(您剛纔提到他們班):

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不會將對字段類的引用轉換爲對字段實例的引用。

您必須明確。也許你忘了括號。

相關問題