Миграции Ошибка в Django: AttributeError: объект 'str' не имеет атрибута '_meta'

Я знаю, что об этом уже спрашивали. Но я попробовал доступные решения. Похоже, что они не работают в моем случае, если только я не пропустил что-то непреднамеренно.

Я удалил все таблицы/отношения из подключенной базы данных и удалил все предыдущие файлы миграции, кроме init.py. Затем запустил команду makemigrations, которая сработала нормально. Но после выполнения команды migrate.

возникла эта ошибка.

Вот ошибка:

Applying book.0001_initial... OK
Applying reader.0001_initial...Traceback (most recent call last):
File "/home/brainiac77/github/bookworms_backend/backend/manage.py", line 22, in <module>
    main()
File "/home/brainiac77/github/bookworms_backend/backend/manage.py", line 18, in main
    execute_from_command_line(sys.argv)
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
    utility.execute()
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv
    self.execute(*args, **cmd_options)
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute
    output = self.handle(*args, **options)
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/base.py", line 98, in wrapped
    res = handle_func(*args, **kwargs)
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 290, in handle
    post_migrate_state = executor.migrate(
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/executor.py", line 131, in migrate
    state = self._migrate_all_forwards(
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/executor.py", line 163, in _migrate_all_forwards
    state = self.apply_migration(
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/executor.py", line 248, in apply_migration
    state = migration.apply(state, schema_editor)
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/migration.py", line 131, in apply
    operation.database_forwards(
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/operations/models.py", line 93, in database_forwards
    schema_editor.create_model(model)
File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 440, in create_model
    if field.remote_field.through._meta.auto_created:
AttributeError: 'str' object has no attribute '_meta'

reader.0001_initial.py

# Generated by Django 4.0.6 on 2022-08-01 07:57

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('book', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Reader',
            fields=[
                ('rid', models.AutoField(primary_key=True, serialize=False)),
                ('photo_url', models.CharField(blank=True, max_length=200, null=True)),
                ('bio', models.CharField(blank=True, max_length=200, null=True)),
                ('read_books', models.ManyToManyField(through='reads.Reads', to='book.book')),
                ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
        ],
        options={
            'db_table': 'reader',
        },
    ),
]

Модель читателя

from django.db import models
from django.contrib.auth.models import User

class Reader(models.Model):
    rid = models.AutoField(primary_key=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    photo_url = models.CharField(max_length=200, blank=True, null=True)
    bio = models.CharField(max_length=200, blank=True, null=True)
    read_books = models.ManyToManyField('book.Book', through='reads.Reads');

    class Meta:
        db_table = 'reader'
    
    def __str__(self):
        return {
            'username': self.user.username,
            'first_name': self.user.first_name,
            'last_name': self.user.last_name,
            'email': self.user.email,
            'photo_url': self.photo_url,
            'bio': self.bio,
        }

Модель книги

from django.db import models

from genre.models import Genre
from reader.models import Reader

class Book(models.Model):
    isbn = models.CharField(max_length=13,primary_key=True)
    title = models.CharField(max_length=255)
    description = models.TextField()
    photo_url = models.CharField(max_length=255)
    page_count = models.IntegerField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    genres = models.ManyToManyField(Genre)
    authors = models.ManyToManyField(Reader, related_name='authored_books')

    class Meta:
        db_table = 'book'
        
    def __str__(self):
        return {
            'isbn': self.isbn,
            'title': self.title,
            'description': self.description,
            'photo_url': self.photo_url,
            'page_count': self.page_count,
            'created_at': self.created_at,
            'updated_at': self.updated_at,
            'genres': self.genres.all(),
            'authors': self.authors.all(),
        }

Читает модель:

from django.db import models

from reader.models import Reader
from book.models import Book

class Reads(models.Model):
    status_choices = (
        ('w', 'Want to Read'),
        ('r', 'Reading'),
        ('c', 'Completed'),
    )
    rsid = models.AutoField(primary_key=True)
    reader = models.ForeignKey(Reader, on_delete=models.CASCADE)
    book = models.ForeignKey(Book, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=1, choices=status_choices)

    class Meta:
        db_table = 'reads'
        
    def __str__(self):
        return {
            'reader': self.reader.user.username,
            'book': self.book.title,
            'created_at': self.created_at,
            'updated_at': self.updated_at,
            'status': self.status,
        }

Что я упускаю?

Мне кажется, что файл миграции (reader.0001_initial.py) неправильный. Там внешний ключ таблицы book.book, который должен быть book.Book.

Думаю, вам нужно очистить все файлы миграции и заново выполнить команду makemigrations.

Вы можете переделать файл миграции для приложения reader, используя следующую команду.

python manage.py reset_migrations reader
Вернуться на верх