2015-09-07 119 views
8

我已經App12/models.py模塊爲:類型錯誤:INT()參數必須是字符串或數字,而不是 'datetime.datetime'

from django.db import models 

class Question(models.Model): 

    ques_text=models.CharField(max_length=300) 
    pub_date=models.DateTimeField('Published date') 

    def __str__(self): 
     return self.ques_text 

class Choice(models.Model): 

    # question=models.ForeignKey(Question) 
    choice_text=models.CharField(max_length=300) 
    votes=models.IntegerField(default=0) 

    def __str__(self): 
     return self.choice_text 

然後我運行CMDS

python manage.py makemigrations App12 
python manage.py migrate 

Question.objects.create(ques_text="How are you?",pub_date='timezone.now()') 
       # and (ques_text="What are you doing?",pub_date='timezone.now()') 

然後,我意識到這個問題,並選擇模型應該是外鍵關係和:

,然後在問題模型進入2條記錄取消對上述評論的語句在型號代碼

當我運行「python manage.py makemigrations App12」,它運行良好,但在那之後,我收到

"TypeError: int() argument must be a string or a number, not 'datetime.datetime" 

錯誤,當我運行「蟒蛇manage.py遷移「命令。

任何人都可以幫助我。我現在可以在Choice模型和Question模型之間添加外鍵關係。

+2

回溯是否提到錯誤在哪裏? – dietbacon

+0

你所評論的ForeignKey有什麼問題? – dietbacon

+0

完全沒有問題。但是當我在做代碼時,發生了這個問題。首先,我忘了添加外鍵關係,但在某個時間之後,我意識到問題和選擇模型之間應該存在外鍵關係。但是執行遷移命令時,它顯示了上述錯誤。爲什麼它會顯示這樣的錯誤,我如何擺脫這個問題。 – Jagat

回答

13

從遷移文件,你得到這個錯誤,這是正常的,你想存儲在一個ForeignKey日期時間這就需要爲一個整型。

當遷移問您將爲舊選擇行設置哪個值時會發生這種情況,因爲需要新的ForeignKey。

要解決該問題,您可以更改遷移文件並將datetime.date ...更改爲問題表中的有效標識,如下面的代碼所示。或者刪除遷移文件並重新運行./manage.py makemigrations,當您詢問默認值時,提示有效的問題ID,而不是日期時間。

from future import unicode_literals 
from django.db import models, migrations 
import datetime 

class Migration(migrations.Migration): 
    dependencies = [ ('App11', '0003_remove_choice_question'), ] 
    operations = [ 
     migrations.AddField(
      model_name='choice', 
      name='question', 
      field=models.ForeignKey(default=1, to='App11.Question'), preserve_default=False,), 
    ] 
+1

刪除「遷移」並重新運行「./manage.py makemigrations」解決了類似的問題。 – Shilpa

2

pub_date不應該是一個字符串。創建對象,如下所示:

from django.utils import timezone 
Question.objects.create(ques_text="How are you?",pub_date=timezone.now()) 
+0

是的,你是對的,pub_date不應該是我的聲明中的字符串pub_date ='timezone.now()',但我應該像︰pub_date = timezone.now(),實際上它是由我寫錯了。但是,問題仍然是一樣的。任何人都可以幫助我,告訴我爲什麼會發生? – Jagat

+0

您可以提供App12/migrations中的文件內容嗎?我懷疑你生成了不正確的遷移。 –

+0

從進口__future__ unicode_literals 從django.db進口車型,遷移 進口日期時間 類遷移(migrations.Migration): 依賴性= [ ( 'App11', '0003_remove_choice_question'), ] 操作= [ 遷移。AddField( model_name ='choice', name ='question', field = models.ForeignKey(default = datetime.date(2015,9,7),to ='App11.Question'), preserve_default = False, ), ] – Jagat

相關問題