2016-03-04 84 views
1

我使用django的用戶模型的所有者外鍵創建此模型。MySQL和Django外鍵到用戶模型

from django.db import models 
from django.contrib.auth.models import User 


class Publicacion(models.Model): 
    titulo = models.CharField(max_length=120) 
    owner = models.ForeignKey(User) 
    contenido = models.TextField() 
    updated = models.DateTimeField(auto_now=True, auto_now_add=False) 
    fechahora = models.DateTimeField(auto_now=False, auto_now_add=True) 

    class Meta: 
     ordering = ['fechahora'] 
     verbose_name_plural = 'Publicaciones' 

    def __unicode__(self): 
     return '%s %s' % (self.titulo, self.contenido) 

但是當我做我得到這個錯誤的遷移:「django.db.utils.OperationalError:(1072,「鍵列‘owner_id’表不存在」)。

我該怎麼辦?

安裝的應用程序

INSTALLED_APPS = (
'django.contrib.admin', 
'django.contrib.auth', 
'django.contrib.contenttypes', 
'django.contrib.sessions', 
'django.contrib.messages', 
'django.contrib.staticfiles', 
'usuarios', 
'publicaciones', 
) 
+0

嘗試刷新數據庫,在這裏可能發佈'sqlmigrate'的內容。 –

+0

DId你先調用'makemigrations'? – schwobaseggl

+0

是的,我沒有錯誤。 –

回答

0

你必須有一列來存儲外鍵在你的MySQL數據庫

模型中的字段必須是這樣的:

owner = models.ForeignKey('auth.User') 

而且數據庫表中的列必須爲:

owner_id  INT(11) 

我不知道爲什麼,但django將「_id」添加到數據庫列名稱。

另外,如果你不想用後綴「_id」數據庫列名,你可以在模型領域補充一點:

db_column='owner' 

所以它必須是:

owner = models.ForeignKey('auth.User',db_column='owner') 

但請記住在數據庫中創建該列。

0

我有問題與外鍵和用戶。我使用OneToOneField,它的工作。