【问题标题】:TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime'TypeError: int() 参数必须是字符串、类似字节的对象或数字,而不是 'datetime.datetime'
【发布时间】:2023-03-29 21:13:01
【问题描述】:

我正在尝试为我的所有模型添加“created_at”字段,但出现以下错误...

TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime'

按顺序,这是我的工作流程...

1) 我在我的模型中加入了created_at = models.DateTimeField(auto_now_add=True)
2) 我运行python manage.py makemigrations,它在我的命令行中显示以下提示...

You are trying to add a non-nullable field 'created_at' to comment without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now()

3) 此时我在所有模型上输入timezone.now(),完成后它成功为我创建了迁移文件。

4) 我运行python manage.py migrate 并得到上面显示的TypeError 消息。

我尝试过的事情...

1) 通过 Stack Overflow 查看类似问题(无济于事)...
2) 删除迁移文件并尝试使用datetime.datetime.now()
3) 删除迁移文件并尝试使用简单整数1

所有这些尝试都没有结果。

完整的命令行回溯...

(env)alopex@Alopex:~/repos/hacker_news$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, sessions, hackernews, contenttypes
Running migrations:
  Rendering model states... DONE
  Applying hackernews.0003_auto_20151226_1701...Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
    utility.execute()
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/core/management/__init__.py", line 342, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 200, in handle
    executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/db/migrations/executor.py", line 92, in migrate
    self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/db/migrations/migration.py", line 123, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards
    field,
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 382, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 145, in column_sql
    default_value = self.effective_default(field)
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 210, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/db/models/fields/related.py", line 910, in get_db_prep_save
    return self.target_field.get_db_prep_save(value, connection=connection)
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 728, in get_db_prep_save
    prepared=False)
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 968, in get_db_prep_value
    value = self.get_prep_value(value)
  File "/home/alopex/repos/hacker_news/env/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 976, in get_prep_value
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime'

完整的迁移文件...

# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-26 17:01
from __future__ import unicode_literals

import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc


class Migration(migrations.Migration):

dependencies = [
    migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ('hackernews', '0002_auto_20151224_1605'),
]

operations = [
    migrations.AddField(
        model_name='comment',
        name='created_at',
        field=models.DateTimeField(auto_now_add=True, default=datetime.datetime(2015, 12, 26, 17, 1, 23, 211181, tzinfo=utc)),
        preserve_default=False,
    ),
    migrations.AddField(
        model_name='comment',
        name='user',
        field=models.ForeignKey(default=datetime.datetime(2015, 12, 26, 17, 1, 28, 128127, tzinfo=utc), on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
        preserve_default=False,
    ),
    migrations.AddField(
        model_name='commentvote',
        name='created_at',
        field=models.DateTimeField(auto_now_add=True, default=datetime.datetime(2015, 12, 26, 17, 1, 34, 85491, tzinfo=utc)),
        preserve_default=False,
    ),
    migrations.AddField(
        model_name='post',
        name='created_at',
        field=models.DateTimeField(auto_now_add=True, default=datetime.datetime(2015, 12, 26, 17, 1, 37, 779457, tzinfo=utc)),
        preserve_default=False,
    ),
    migrations.AddField(
        model_name='postvote',
        name='created_at',
        field=models.DateTimeField(auto_now_add=True, default=datetime.datetime(2015, 12, 26, 17, 1, 41, 794803, tzinfo=utc)),
        preserve_default=False,
    ),
]

【问题讨论】:

    标签: python django datetime


    【解决方案1】:

    问题在于新的ForeignKey

    migrations.AddField(
        model_name='comment',
        name='user',
        field=models.ForeignKey(default=datetime.datetime(2015, 12, 26, 17, 1, 28, 128127, tzinfo=utc), on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
        preserve_default=False,
    ),
    

    显然默认值是错误的。我想你是插错了。

    您应该指定用户的主键,或者提供User 对象。

    【讨论】:

    • 你在哪里添加的?
    【解决方案2】:

    我以非常干净的方式解决了这个问题。这是您需要做的事情

    • 进入迁移文件夹并搜索您要迁移的模型的迁移文件。你会发现,它的默认设置为timezone.now

    • 将其更改为无默认值(删除default 配置)并设置null=True blank=True

    • 运行python manage.py migrate

    这应该可以解决它。

    【讨论】:

      【解决方案3】:

      我也遇到过类似的问题,我想分享一下我是如何解决这个问题的,因为这可能对其他人有益。在 Django 文档中几乎没有具体信息的情况下,这是一个难以解决的挑战,而且这个线程似乎是 stackoverflow 上措辞最好的问题。

      我的情况:

      • 我是 Django 新手,正在试验和使用 SQLLite 数据库模型
      • 我创建了一个简单的模型,在迁移过程中被问到有关提供一次性默认值的问题,我提供了这个问题
      • 从这一点开始,迁移过程不会忘记这个默认值,我无法进一步迁移并卡住了

      我的解决方案:

      • 鉴于我不是在生产中,也不是在大规模开发中,我采用了杀死数据库和所有迁移然后再次迁移的方法,从而解决了问题
      • 注意:如果您在数据库中拥有既定数据,请先备份数据或寻求其他指导 - 有其他线程显示如何执行此备份和恢复,即使在数据库管理系统之间也是如此
      • 在项目根目录下,查找文件 db.sqlite3 并重命名或删除它,这将强制在下次迁移时重新创建它
      • migrations 文件夹下删除所有迁移 .py 文件 - 这将防止在重新创建数据库时再次应用这些文件
      • 再次运行 migrate - 这将创建一个干净的数据库,而不会尝试恢复默认值

      我承认我的方法有点不合时宜,但它对我有用,而且对我的模型没有任何损害,这些模型都是完美创建的 - 我还修复了导致问题的默认值的缺失我在为整数字段输入字符默认值时犯了一个错误。但是,如果您进一步进行开发,可能会产生副作用,我欢迎您提出更安全的方法来解决此问题。

      【讨论】:

      • 这实际上是最好的答案,我必须在我工作之前删除所有迁移文件
      【解决方案4】:

      这些解决方案都不适合我。但是,当我删除项目中我的 app 文件夹中 migrations 文件夹中的所有文件并运行 python manage.py migrate 时,一切正常,不再有问题。

      【讨论】:

        【解决方案5】:

        我遇到了同样的问题,我已经按照上面的建议进行了尝试,我只删除了导致此问题的迁移文件(应用python manage.py makemigrations 时创建的最新文件),我再次运行python manage.py makemigrations,在这里我注意到之前我已经将 &gt;&gt;&gt; timezone.now() 作为 ForeignKey 字段的默认值,这次我在我的 models.py 文件中设置了默认值,我的问题就解决了。

        注意:迁移时不要为 ForeignKeys 提供默认值。

        【讨论】:

          【解决方案6】:

          对我来说,当我打开未迁移的文件并在 ForeignKey 上我用逗号分隔值 null=True、blank=True 时它起作用了。

          field=models.ForeignKey(null=True, blank=True, on_delete=django.db.models.deletion.CASCADE, to='your_app.Model')

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-01-14
            • 2018-03-17
            • 2017-07-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-10
            相关资源
            最近更新 更多