2016-11-12 109 views
0

我想通過外鍵將型號發佈與型號主題鏈接。當我運行makemigrations命令時,它會引發一個導入錯誤,並說名稱'Topic'沒有被定義。這可能是什麼原因?它當然似乎被定義。我幾乎排除,這是不是在數據庫內的問題。名稱錯誤:無法導入[型號名稱]

class Post(models.Model): 
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)   
    title = models.CharField(max_length=100) 
    summary = models.TextField(blank=True, null=True) 
    content = models.TextField() 
    draft = models.BooleanField(default=False) 
    details = models.CharField(blank=True, null=True, max_length=250) 
    updated = models.DateTimeField(auto_now=True, auto_now_add=False) 
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) 
    topic = models.ForeignKey(Topic, blank=True, null=True) 
    thumbnail = models.ImageField(upload_to='media', blank=True, null=True) 


    def get_absolute_url(self): 
     return reverse('posts:detail', kwargs={'pk': self.pk}) 

    def __str__(self): 
     return self.title 


class Topic(models.Model): 
    name = models.CharField(max_length=50) 
    description = models.TextField() 
    picture = models.ImageField(upload_to='media', blank=True, null=True) 
    isperson = models.BooleanField(default=False) 
    ispolicy = models.BooleanField(default=False) 
    positive = models.BooleanField(default=True) 
    percent = models.CharField(max_length=5) 

    def __str__(self): 
     return self.name 

任何想法?我沒有看到這段代碼中有任何問題,我的IDE也沒有識別出這個模型主題

回答

1

我在考慮你已經在你的文件中正確縮進了Post模型的代碼。

解決方案:嘗試定義Post上面的主題。

0

首先,這

topic = models.ForeignKey(Topic, blank=True, null=True) 

應該是這個

topic = models.ForeignKey('Topic', blank=True, null=True) 

這樣,它告訴Django,你設置的外鍵的模型,這是尚未宣佈,但會在代碼中進一步聲明。

其次,你應該正確地縮進安置自己的模型,其方法:

class Post(models.Model): 
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True) 
    title = models.CharField(max_length=100) 
    summary = models.TextField(blank=True, null=True) 
    content = models.TextField() 
    draft = models.BooleanField(default=False) 
    details = models.CharField(blank=True, null=True, max_length=250) 
    updated = models.DateTimeField(auto_now=True, auto_now_add=False) 
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) 
    topic = models.ForeignKey('Topic', blank=True, null=True) 
    thumbnail = models.ImageField(upload_to='media', blank=True, null=True) 

    def get_absolute_url(self): 
     return reverse('posts:detail', kwargs={'pk': self.pk}) 

    def __str__(self): 
     return self.title 

因爲你現在擁有它,Django不明白,沒有鋸齒的領域屬於Post模型。