Django: FieldError: 无法将关键字'name'解析为字段。可选项有: Name, id

0 投票
1 回答
46 浏览
提问于 2025-04-12 13:04

我刚开始学习Django,正在跟着这个教程:Django教程第三部分:使用模型,在链接的步骤中遇到了这个问题。

  • 我输入了命令:python3 manage.py makemigrations
  • 接着又输入了:python3 manage.py migrate

在执行第二个命令后,出现了错误。

完整的错误信息是:

PS E:\DjangoDrill\locallibrary> python manage.py migrate       
Operations to perform:
  Apply all migrations: admin, auth, catalog, contenttypes, sessions
Running migrations:
  Applying catalog.0001_initial...Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line
    utility.execute()
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\core\management\__init__.py", line 436, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\core\management\base.py", line 412, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\core\management\base.py", line 458, in execute
    output = self.handle(*args, **options)
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\core\management\base.py", line 106, in wrapper
    res = handle_func(*args, **kwargs)
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\core\management\commands\migrate.py", line 356, in handle
    post_migrate_state = executor.migrate(
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\migrations\executor.py", line 135, in migrate
    state = self._migrate_all_forwards(
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\migrations\executor.py", line 167, in _migrate_all_forwards
    state = self.apply_migration(
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\migrations\executor.py", line 252, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\migrations\migration.py", line 132, in apply
    operation.database_forwards(
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\migrations\operations\models.py", line 1135, in database_forwards
    schema_editor.add_constraint(model, self.constraint)
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\backends\sqlite3\schema.py", line 562, in add_constraint
    super().add_constraint(model, constraint)
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\backends\base\schema.py", line 532, in add_constraint
    sql = constraint.create_sql(model, self)
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\models\constraints.py", line 239, in create_sql
    expressions = self._get_index_expressions(model, schema_editor)
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\models\constraints.py", line 211, in _get_index_expressions
    return ExpressionList(*index_expressions).resolve_expression(
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\models\expressions.py", line 950, in resolve_expression
    c.source_expressions[pos] = arg.resolve_expression(
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\models\indexes.py", line 264, in resolve_expression
    resolve_root_expression = root_expression.resolve_expression(
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\models\expressions.py", line 950, in resolve_expression
    c.source_expressions[pos] = arg.resolve_expression(
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\models\expressions.py", line 829, in resolve_expression
    return query.resolve_ref(self.name, allow_joins, reuse, summarize)
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\models\sql\query.py", line 1977, in resolve_ref
    join_info = self.setup_joins(
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\models\sql\query.py", line 1824, in setup_joins
    path, final_field, targets, rest = self.names_to_path(
  File "C:\Users\Narea\AppData\Roaming\Python\Python38\site-packages\django\db\models\sql\query.py", line 1725, in names_to_path
    raise FieldError(
django.core.exceptions.FieldError: Cannot resolve keyword 'name' into field. Choices are: Name, id

这是我的代码:

models.py文件内容:

from django.db import models
from django.urls import reverse
from django.db.models import UniqueConstraint
from django.db.models.functions import Lower
import uuid

class Genre(models.Model):
    name = models.CharField(max_length=200, unique=True, help_text="Enter a book genre")

    def get_absolute_url(self):
        return reverse('genre-detail', args=[str(self.id)])

    def __str__(self):
        return self.name

    class Meta:
        constraints = [
            UniqueConstraint(
                Lower('name'),
                name='genre_name_case_insensitive_unique',
                violation_error_message = "Genre already exists (case insensitive match)"
            ),
        ]

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey('Author', on_delete=models.RESTRICT, null=True)
    summary = models.TextField(max_length=1000, help_text="Brief the story of the book")
    isbn = models.CharField(max_length=13, unique=True, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn''">ISBN number</a>')
    genre = models.ManyToManyField(Genre, help_text="Genres for the book")
    def __str__(self):
        return self.title
    def get_absolute_url(self):
        return reverse('book-detail', args=[str(self.id)])

class BookInstance(models.Model):
    id = models.UUIDField(primary_key=True, default= uuid.uuid4, help_text="Unique ID for this particular book across whole library")
    book = models.ForeignKey('Book', on_delete=models.RESTRICT, null=True)
    imprint = models.CharField(max_length=200)
    due_back = models.DateField(null=True, blank=True)

    LOAN_STATUS = (
        ('m', 'Maintenance'),
        ('o', 'On loan'),
        ('a', 'Available'),
        ('r', 'Reserved'),
    )

    status = models.CharField(
        max_length=1,
        choices=LOAN_STATUS,
        blank=True,
        default='m',
        help_text='Book availability',
    )

    class Meta:
        ordering = ['due_back']

    def __str__(self):
        return f'{self.id}({self.book.title})'

class Author(models.Model):
    """Model representing an author."""
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    date_of_birth = models.DateField(null=True, blank=True)
    date_of_death = models.DateField('Died', null=True, blank=True)

    class Meta:
        ordering = ['last_name', 'first_name']

    def get_absolute_url(self):
        """Returns the URL to access a particular author instance."""
        return reverse('author-detail', args=[str(self.id)])

    def __str__(self):
        """String for representing the Model object."""
        return f'{self.last_name}, {self.first_name}'

admin.py文件内容:

from django.contrib import admin

from .models import Author, Genre, Book, BookInstance#, Language

admin.site.register(Book)
admin.site.register(Author)
admin.site.register(Genre)
admin.site.register(BookInstance)
# admin.site.register(Language)

catalog迁移0001_initial的内容:

# Generated by Django 4.2.11 on 2024-03-28 07:37

from django.db import migrations, models
import django.db.models.deletion
import django.db.models.functions.text
import uuid


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Author',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('first_name', models.CharField(max_length=100)),
                ('last_name', models.CharField(max_length=100)),
                ('date_of_birth', models.DateField(blank=True, null=True)),
                ('date_of_death', models.DateField(blank=True, null=True, verbose_name='Died')),
            ],
            options={
                'ordering': ['last_name', 'first_name'],
            },
        ),
        migrations.CreateModel(
            name='Book',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=200)),
                ('summary', models.TextField(help_text='Brief the story of the book', max_length=1000)),
                ('isbn', models.CharField(help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>', max_length=13, unique=True)),
            ],
        ),
        migrations.CreateModel(
            name='BookInstance',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, help_text='Unique ID for this particular book across whole library', primary_key=True, serialize=False)),
                ('imprint', models.CharField(max_length=200)),
                ('due_back', models.DateField(blank=True, null=True)),
                ('status', models.CharField(blank=True, choices=[('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved')], default='m', help_text='Book availability', max_length=1)),
            ],
            options={
                'ordering': ['due_back'],
            },
        ),
        migrations.CreateModel(
            name='Genre',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('Name', models.CharField(help_text='Enter a book genre', max_length=200, unique=True)),
            ],
        ),
        migrations.AddConstraint(
            model_name='genre',
            constraint=models.UniqueConstraint(django.db.models.functions.text.Lower('name'), name='genre_name_case_insensitive_unique', violation_error_message='Genre already exists'),
        ),
        migrations.AddField(
            model_name='bookinstance',
            name='book',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.RESTRICT, to='catalog.book'),
        ),
        migrations.AddField(
            model_name='book',
            name='author',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.RESTRICT, to='catalog.author'),
        ),
        migrations.AddField(
            model_name='book',
            name='genre',
            field=models.ManyToManyField(help_text='Genres for the book', to='catalog.genre'),
        ),
    ]

我查找了一些类似的问题,但没有找到和我的问题很相关的解决方案。

1 个回答

0

目前在模型 Genre 中没有 Name 这个字段,但有一个 name 字段。catalog migration 0001_initial 表明这并不是一直如此,某个时候这个情况发生了变化。

migrations.CreateModel(
    name='Genre',
    fields=[
        ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
        ('Name', models.CharField(help_text='Enter a book genre', max_length=200, unique=True)),
    ],     ^
),         |- - Added initially

最简单的解决办法就是直接把数据库删掉,然后重新开始。当然,这样做不太专业,但如果没有什么值得保留的东西,那就没必要给自己增加压力了。

其实有很多解决方案,我会尝试一些,然后再回来分享测试结果。

撰写回答