TypeError:int()参数必须是字符串或数字,而不是'datetime.datetime'

Jag*_*gat 11 python django django-orm

我将App12/models.py模块设为:

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
Run Code Online (Sandbox Code Playgroud)

然后我运行cmds

 python manage.py makemigrations App12
 python manage.py migrate
Run Code Online (Sandbox Code Playgroud)

然后在问题模型中输入2条记录:

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

然后我意识到问题和选择模型应该是外键关系,并在模型代码中取消注释上面注释的语句

当我运行" python manage.py makemigrations App12"时,它运行良好,但在那之后,我得到了

"TypeError: int() argument must be a string or a number, not 'datetime.datetime"
Run Code Online (Sandbox Code Playgroud)

我正在运行"python manage.py migrate"命令时出错.

任何人都可以帮助我.如何在Choice模型和问题模型之间添加外键关系.

Mou*_*nir 16

从您的迁移文件中,您收到此错误是正常的,您正在尝试将日期时间存储在需要为int的Foreignkey上.

当迁移询问您将为旧的Choice行设置哪个值时会发生这种情况,因为需要新的ForeignKey.

要解决此问题,您可以更改迁移文件并将datetime.date ...更改为Question表中的有效ID,如下面的代码所示.或者删除迁移文件并重新运行./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, ),
    ]
Run Code Online (Sandbox Code Playgroud)