2017-03-03 68 views
-1

進口我有這樣的模式在我的models.py顯示錯誤與Django的MySQL表

class DeviceType(models.Model): 
    device_type_id = models.IntegerField(unique=True, blank=True, null=True,db_column='device_type_id') 
    device_type_name = models.CharField(max_length=64) 

class Meta: 
    # managed = False 
    db_table = 'device_type' 

因爲我試圖將表添加到管理員查看測試,它的加入,但是當我嘗試看看結果我有一個錯誤:

(1054, "Unknown column 'device_type.id' in 'field list'") 
Request Method: GET 
Request URL: http://172.17.45.9:8001/admin/_my_alfanet_/devicetype/ 
Django Version: 1.10.6 
Exception Type: OperationalError 
Exception Value:  
(1054, "Unknown column 'device_type.id' in 'field list'") 
Exception Location: /etc/network/scripts/my_alfanet_env/lib/python2.7/site-packages/MySQLdb/connections.py in defaulterrorhandler, line 36 
Python Executable: /etc/network/scripts/my_alfanet_env/bin/python 
Python Version: 2.7.9 
Python Path:  
['/etc/network/scripts', 
'/etc/network/scripts/ansible/lib', 
'/etc/network/scripts', 
'/etc/network/scripts/my_alfanet_env/lib/python27.zip', 
'/etc/network/scripts/my_alfanet_env/lib/python2.7', 
'/etc/network/scripts/my_alfanet_env/lib/python2.7/plat-linux2', 
'/etc/network/scripts/my_alfanet_env/lib/python2.7/lib-tk', 
'/etc/network/scripts/my_alfanet_env/lib/python2.7/lib-old', 
'/etc/network/scripts/my_alfanet_env/lib/python2.7/lib-dynload', 
'/usr/local/lib/python2.7', 
'/usr/local/lib/python2.7/plat-linux2', 
'/usr/local/lib/python2.7/lib-tk', 
'/etc/network/scripts/my_alfanet_env/lib/python2.7/site-packages'] 
Server time: Fri, 3 Mar 2017 15:18:57 +0000 

它看起來像的Django嘗試將其自身的列添加到SQL請求,這是創建一個錯誤。誰可以提供幫助,這個問題有哪些解決方案?

+0

這個數據庫是外部的,它從另一個項目導入 –

+0

你添加了管理視圖admin.py文件嗎? – alfredo138923

回答

0

Django要求每個模型只有一個主鍵。它automatically adds a primary key fieldid到模型,除非您爲其他字段之一設置primary_key=True

就你而言,看起來好像device_type_id是主鍵。如果是這樣,你可以改變模式:

class DeviceType(models.Model): 
    device_type_id = models.IntegerField(primary_key=True) 
    device_type_name = models.CharField(max_length=64) 

我已經刪除db_column='device_type_id',因爲它的字段名稱相匹配。我也刪除了blank=Truenull=True,因爲主鍵不能爲空。

如果您的數據庫自動創建device_type_id,那麼您應該使用AutoField而不是IntegerField。否則,在數據庫中創建新設備類型時,必須手動設置device_type_id

+0

是的,這樣一切都很好。謝謝! –