Python 类型错误:int() 参数必须是字符串、类似字节的对象或数字,而不是“datetime.datetime”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34473323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:03:17  来源:igfitidea点击:

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

pythondjangodatetime

提问by Erik ?sland

I am attempting to add a 'created_at' field for all my models and am getting the following error...

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

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

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

In order, this is my work flow...

1) I put created_at = models.DateTimeField(auto_now_add=True)in my models.
2) I run python manage.py makemigrationsand it displays the following prompt in my command line...

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

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) At this point I type in timezone.now()on all of the models and when finished it successfully creates the migrations file for me.

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

4) I run python manage.py migrateand get the TypeErrormessage displayed above.

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

Things I have tried...

我尝试过的事情...

1) Looking through Stack Overflow for similar issues (to no avail)...
2) Deleteing the migrations file and attempting to use datetime.datetime.now()
3) Deleteing the migrations file and attempting to use the simple integer 1.

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

All of these attempts have been fruitless.

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

Full command line traceback...

完整的命令行回溯...

(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'

Full migration file...

完整的迁移文件...

# -*- 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,
    ),
]

采纳答案by Andrea Corbellini

The problem is with the new ForeignKey:

问题出在新的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,
),

Clearly the default value is wrong. I think you have inserted it by mistake.

显然默认值是错误的。我认为您误插入了它。

You should either specify the primary key of a user, or give a Userobject.

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

回答by Roger Layton

I have had a similar problem and I would like to share how I solved this as it may be of benefit to others. This was a challenge to solve with little specific information from the Django documentation and this thread appears to be the best-phrased question on stackoverflow.

我遇到了类似的问题,我想分享我如何解决这个问题,因为它可能对其他人有益。这是一个挑战,在 Django 文档中几乎没有具体信息,这个线程似乎是关于 stackoverflow 的最佳措辞问题。

My situation:

我的情况:

  • I am new to Django and experimenting, and using the SQLLite database model
  • I had created a simple model, and during the migrate is asked the question about providing a one-off default, which I provided
  • From this point on the migrate process would not forget this default, and I could not migrate this further and was stuck
  • 我是 Django 的新手,正在试验和使用 SQLLite 数据库模型
  • 我创建了一个简单的模型,在迁移过程中被问到有关提供一次性默认值的问题,我提供了
  • 从这一点开始,迁移过程不会忘记这个默认值,我无法进一步迁移并被卡住了

My solution:

我的解决方案:

  • Given that I am not in production and also not in large-scale development I adopted the approach to kill the database and all of the migrations and then to migrate again, which solved the problem
  • NOTE: If you have vested data in the database, then back up the data first or seek other guidance - there are other threads which show how to do this backup and restore, even between database management systems
  • under the project root, look for the file db.sqlite3and rename or delete this which will force this to be recreated on the next migrate
  • under the migrationsfolder delete ALL of the migrations .pyfiles - this will prevent these from being applied again when the database is recreated
  • run migrate again - which will create a clean database without attempting to reinstate the default
  • 鉴于我不在生产中,也不在大规模开发中,我采用了杀死数据库和所有迁移然后再次迁移的方法,解决了问题
  • 注意:如果您已在数据库中授予数据,则首先备份数据或寻求其他指导 - 有其他线程显示如何进行此备份和恢复,即使在数据库管理系统之间
  • 在项目根目录下,查找文件db.sqlite3并重命名或删除它,这将强制在下一次迁移时重新创建它
  • 迁移文件夹下删除所有迁移.py文件 - 这将防止在重新创建数据库时再次应用这些文件
  • 再次运行 migrate - 这将创建一个干净的数据库而不尝试恢复默认值

I accept that my approach is a bit of a hack but it worked for me, and also without any damage to my models which were all created perfectly - I did also fix the lack of the default which was causing the problem which was a mistake of mine in entering a char default for an integer field. However, there may be side-effects if you are further into your development and I would welcome suggestions on a safer approach to this problem.

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

回答by Kumar Raja

I have faced the same problem, I have tried as suggested above and I deleted only my migration file which is causing this issue (latest file created while applying python manage.py makemigrations), again I run python manage.py makemigrations, here I notice that previously I have given >>> timezone.now()as default for ForeignKey Field, this time I have set default value in my models.py file and my problem was solved.

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

Note: don't provide default values for ForeignKeys while migrating.

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

回答by Alex Jolig

None of those solutions work for me. But when I removedall files from migrationsfolder in my app folder in project and ran python manage.py migrate, everything worked fine and there were no more problems.

这些解决方案都不适合我。但是当我从项目中应用程序文件夹中的迁移文件夹中删除所有文件并运行时,一切正常,没有更多问题。python manage.py migrate

回答by Ezplora

I fixed this in a very clean way. Here is what you need to do

我以一种非常干净的方式解决了这个问题。这是你需要做的

  • Go to migrations folder and search for the migration file of the model you want to migrate. you will find that, it has a default set to timezone.now

  • Change that to no default(remove the defaultconfig) and set null=True blank=True

  • Run python manage.py migrate

  • 转到迁移文件夹并搜索要迁移的模型的迁移文件。你会发现,它有一个默认设置为timezone.now

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

  • python manage.py migrate

And that should fix it.

这应该解决它。

回答by Lukasz

For me it worked when i opened not migrated file and on ForeignKey i separated the values null=True, blank=True with the comma in between.

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

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

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