繁体   English   中英

Django 中的迁移错误:AttributeError: 'str' object 没有属性 '_meta'

[英]Migrations Error in Django: AttributeError: 'str' object has no attribute '_meta'

我知道以前有人问过这个问题。 但是,我尝试了可用的解决方案。 除非我无意中错过了某些东西,否则这些似乎对我不起作用。

我从连接的数据库中删除了所有表/关系,并删除了除init .py 之外的所有以前的迁移文件。 然后运行运行良好的 makemigrations 命令。 但是运行迁移后出现此错误。

这是错误:

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',
        },
    ),
]

阅读器 model

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,
        }

预订 Model

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(),
        }

读取 Model:

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,
        }

INSTALLED_APPS

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # local apps
    'rest_framework',
    'rest_framework.authtoken',
    'reader',
    'book',
    'genre',
    'reads',
    'bookreview',
    'library',
    'librarystock',
    'bookborrow',
    'friend',
]

我错过了什么?

我认为迁移文件(reader.0001_initial.py)是错误的。 那里的外键表是book.book ,应该是book.Book

所以我认为您需要清除所有迁移文件并重新运行makemigrations命令。

您可以使用以下命令重新制作reader应用程序的迁移文件。

python manage.py reset_migrations reader

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM