Django: FieldError: невозможно преобразовать ключевое слово «имя» в поле. Возможные варианты: имя, идентификатор.Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Django: FieldError: невозможно преобразовать ключевое слово «имя» в поле. Возможные варианты: имя, идентификатор.

Сообщение Anonymous »

Просто начните работать с Django. Я следил за этим руководством: Учебное пособие по Django, часть 3. Использование моделей, и я столкнулся с этой проблемой на связанном шаге.
  • 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 
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 [url=https://www.isbn-international.org/content/what-isbn]ISBN number[/url]')
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 [url=https://www.isbn-international.org/content/what-isbn]ISBN number[/url]', 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'),
),
]
Я проверил несколько похожих проблем, но не нашел решений, тесно связанных с моей проблемой.

Подробнее здесь: https://stackoverflow.com/questions/782 ... s-are-name
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»