首页 > 解决方案 > TypeError:字段“id”需要一个数字,但得到了

问题描述

我正在使用 Django,最近在 models.py 中重新制作了我的帖子模型,但是每当我尝试进行迁移时,我都会收到以下错误。

Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
  Applying blog.0006_post_author...Traceback (most recent call last):
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get_prep_value
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'User'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 369, in execute
    output = self.handle(*args, **options)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\migrate.py", line 231, in handle
    post_migrate_state = executor.migrate(
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\migration.py", line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\operations\fields.py", line 110, in database_forwards
    schema_editor.add_field(
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\schema.py", line 328, in add_field
    self._remake_table(model, create_field=field)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\schema.py", line 189, in _remake_table
    self.effective_default(create_field)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\base\schema.py", line 303, in effective_default
    return field.get_db_prep_save(self._effective_default(field), self.connection)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related.py", line 939, in get_db_prep_save
    return self.target_field.get_db_prep_save(value, connection=connection)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 821, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 2365, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1774, in get_prep_value
    raise e.__class__(
TypeError: Field 'id' expected a number but got <User: >.

这是我的 models.py 文件:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import pre_save
from django.utils.text import slugify
from django.conf import settings
from django.db.models.signals import post_delete
from django.dispatch import receiver
from PIL import Image

def upload_location(instance, filename, **kwargs):
    file_path = 'blog/{author.id}/{title}-{filename}'.format(
    author_id = str(instance.author.id), title=str(instance.title), filename=filename
    )
    return file_path

class BlogPost(models.Model):
    title           = models.CharField(max_length=50, null=False, blank=False)
    description     = models.CharField(max_length=500, null=False, blank=False)
    image           = models.ImageField(upload_to=upload_location, null=False, blank=False)
    date_published  = models.DateTimeField(auto_now_add=True, verbose_name="date published")
    date_updated    = models.DateTimeField(auto_now=True, verbose_name="date updated")
    author          = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    slug            = models.SlugField(blank=True, unique=True)

    def __str__(self):
        return self.title

@receiver(post_delete, sender=BlogPost)
def submission_delete(sender, instance, **kwargs):
    instance.image.delete(False)

def pre_save_blog_post_reciever(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = slugify(instance.author.username + "-" + instance.title)

pre_save.connect(pre_save_blog_post_reciever, sender=BlogPost)

这是我的 admin.py 文件:

from django.contrib import admin
from .models import BlogPost
# Register your models here.
admin.site.register(BlogPost)

标签: pythonpython-3.xdjangopython-2.7

解决方案


代替:

file_path = 'blog/{author.id}/{title}-{filename}'.format(
    author_id = str(instance.author.id), title=str(instance.title), filename=filename
)

和:

file_path = 'blog/{author_id}/{title}-{filename}'.format(
    author_id = str(instance.author.id), title=str(instance.title), filename=filename
    )

author.id注意where .should be的错字_


推荐阅读