2015-09-07 120 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

相关问题