Django:FieldError:无法将关键字“名称”解析为字段。选项有:名称、id

问题描述 投票:0回答:1

开始使用 Django。我正在关注本教程:Django 教程第 3 部分:使用模型,我在链接步骤中遇到了这个问题

  • python3 管理.py makemigrations
  • python3 管理.py 迁移

执行第二条命令后出现错误。

完整错误消息:

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)

目录迁移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'),
        ),
    ]

我检查过一些类似的问题,但我没有发现那些解决方案与我的问题非常相关。

python django django-models
1个回答
0
投票

目前模型中没有

Name
字段
Genre
,但有一个
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

最简单的解决方案是灾难性的数据库删除并重新启动。当然,这很不专业,但如果没有什么可以节省/奋斗的,为什么要给自己施加压力呢?

有一千零一个解决方案,我将研究其中一些并返回测试解决方案。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.