gpt4 book ai didi

django - 单个应用程序中的 ValueError ('Related model %r cannot be resolved' % self.remote_field.model)

转载 作者:行者123 更新时间:2023-12-04 01:36:29 25 4
gpt4 key购买 nike

Django 3.0、Python 3.7.5

这是models.py

from django.db import models

class Owner(models.Model):
first_name = models.CharField('Ім`я', max_length=30)
last_name = models.CharField('Фамілія', max_length=30)
surname = models.CharField('По-батькові', max_length=30)

class Address(models.Model):
owner = models.ForeignKey(Owner, on_delete=models.CASCADE, verbose_name='Власник')
house = models.IntegerField('Будинок', default=0)
street = models.CharField('Вулиця', max_length=30)
city = models.CharField('Місто', max_length=30)
region = models.CharField('Область', max_length=30)
cantry = models.CharField('Країна', max_length=30)

class Car(models.Model):
number = models.IntegerField('Номер', primary_key=True)
date = models.CharField('Місто', max_length=30)
brand = models.CharField('Марка', max_length=30)
colors = models.CharField('Кольори', max_length=30)
state = models.CharField('Стан', max_length=30)
owner = models.ForeignKey(Owner, on_delete=models.CASCADE, verbose_name='Власник')
address = models.ForeignKey(Address, on_delete=models.CASCADE, verbose_name='Адреса')

class Engine(models.Model):
car = models.ForeignKey(Car, on_delete=models.CASCADE, verbose_name='Машина')
cylinders = models.CharField('Циліндри', max_length=30)
fuel_injection = models.CharField('Вприскування пального', max_length=30)
supercharger = models.CharField('Суперчарджер', max_length=30)
catalytic = models.CharField('Каталізатор', max_length=30)
automatic = models.CharField('Автоматичний', max_length=4)

class Performance(models.Model):
car = models.OneToOneField(Car, on_delete=models.CASCADE, parent_link=True, verbose_name='Машина')
# car = models.ForeignKey('Машина', Car, on_delete=models.CASCADE)
acceleration = models.FloatField('0-100 kmph (сек)', default=0)
max_speed = models.IntegerField('Максимальна швидкість', default=0)
fuel_eff = models.FloatField('Витрата пального', default=0)
pollution_class = models.CharField('Клас забруднення', max_length=8)
base_price = models.IntegerField('Базова ціна', default=0)

class Type(models.Model):
car = models.OneToOneField(Car, on_delete=models.CASCADE, parent_link=True, verbose_name='Машина')
# car = models.ForeignKey('Машина', Car, on_delete=models.CASCADE)
body_type = models.CharField('Тип кузова', max_length=16)
no_of_door = models.IntegerField('Кількість дверей', default=0)
no_of_seats = models.IntegerField('Кількість сидіннь', default=0)
engine_place = models.CharField('Місце мотору', max_length=2)
drivetrain = models.CharField('Привід', max_length=16)

class Body(models.Model):
car = models.OneToOneField(Car, on_delete=models.CASCADE, parent_link=True, verbose_name='Машина')
# car = models.ForeignKey('Машина', Car, on_delete=models.CASCADE)
wheel_base = models.IntegerField('Колісна база', default=0)
track_front = models.IntegerField('Передня колія', default=0)
track_rear = models.IntegerField('Задня колія', default=0)
length = models.IntegerField('Довжина', default=0)
width = models.IntegerField('Ширина', default=0)
height = models.IntegerField('Висота', default=0)

这里是创建迁移0001_initial.py

# Generated by Django 3.0 on 2019-12-15 08:59

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


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Address',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('house', models.IntegerField(default=0, verbose_name='Будинок')),
('street', models.CharField(max_length=30, verbose_name='Вулиця')),
('city', models.CharField(max_length=30, verbose_name='Місто')),
('region', models.CharField(max_length=30, verbose_name='Область')),
('cantry', models.CharField(max_length=30, verbose_name='Країна')),
],
),
migrations.CreateModel(
name='Body',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('car', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, parent_link=True, to='polls.Car', verbose_name='Машина')),
('wheel_base', models.IntegerField(default=0, verbose_name='Колісна база')),
('track_front', models.IntegerField(default=0, verbose_name='Передня колія')),
('track_rear', models.IntegerField(default=0, verbose_name='Задня колія')),
('length', models.IntegerField(default=0, verbose_name='Довжина')),
('width', models.IntegerField(default=0, verbose_name='Ширина')),
('height', models.IntegerField(default=0, verbose_name='Висота')),
],
),
migrations.CreateModel(
name='Car',
fields=[
('number', models.IntegerField(primary_key=True, serialize=False, verbose_name='Номер')),
('date', models.CharField(max_length=30, verbose_name='Місто')),
('brand', models.CharField(max_length=30, verbose_name='Марка')),
('colors', models.CharField(max_length=30, verbose_name='Кольори')),
('state', models.CharField(max_length=30, verbose_name='Стан')),
('address', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Address', verbose_name='Адреса')),
],
),
migrations.CreateModel(
name='Owner',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=30, verbose_name='Ім`я')),
('last_name', models.CharField(max_length=30, verbose_name='Фамілія')),
('surname', models.CharField(max_length=30, verbose_name='По-батькові')),
],
),
migrations.CreateModel(
name='Performance',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('car', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, parent_link=True, to='polls.Car', verbose_name='Машина')),
('acceleration', models.FloatField(default=0, verbose_name='0-100 kmph (сек)')),
('max_speed', models.IntegerField(default=0, verbose_name='Максимальна швидкість')),
('fuel_eff', models.FloatField(default=0, verbose_name='Витрата пального')),
('pollution_class', models.CharField(max_length=8, verbose_name='Клас забруднення')),
('base_price', models.IntegerField(default=0, verbose_name='Базова ціна')),
],
),
migrations.CreateModel(
name='Type',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('car', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, parent_link=True, to='polls.Car', verbose_name='Машина')),
('body_type', models.CharField(max_length=16, verbose_name='Тип кузова')),
('no_of_door', models.IntegerField(default=0, verbose_name='Кількість дверей')),
('no_of_seats', models.IntegerField(default=0, verbose_name='Кількість сидіннь')),
('engine_place', models.CharField(max_length=2, verbose_name='Місце мотору')),
('drivetrain', models.CharField(max_length=16, verbose_name='Привід')),
],
),
migrations.CreateModel(
name='Engine',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('cylinders', models.CharField(max_length=30, verbose_name='Циліндри')),
('fuel_injection', models.CharField(max_length=30, verbose_name='Вприскування пального')),
('supercharger', models.CharField(max_length=30, verbose_name='Суперчарджер')),
('catalytic', models.CharField(max_length=30, verbose_name='Каталізатор')),
('automatic', models.CharField(max_length=4, verbose_name='Автоматичний')),
('car', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Car', verbose_name='Машина')),
],
),
migrations.AddField(
model_name='car',
name='owner',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Owner', verbose_name='Власник'),
),
migrations.AddField(
model_name='address',
name='owner',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Owner', verbose_name='Власник'),
),
]

这是错误

(ENV) [b@l mysite]$ python manage.py migrate polls
Operations to perform:
Apply all migrations: polls
Running migrations:
Applying polls.0001_initial...Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/home/b/django/ENV/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/b/django/ENV/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/b/django/ENV/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/b/django/ENV/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/home/b/django/ENV/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/home/b/django/ENV/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 233, in handle
fake_initial=fake_initial,
File "/home/b/django/ENV/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/b/django/ENV/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/b/django/ENV/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/b/django/ENV/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/b/django/ENV/lib/python3.7/site-packages/django/db/migrations/operations/models.py", line 92, in database_forwards
schema_editor.create_model(model)
File "/home/b/django/ENV/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 322, in create_model
sql, params = self.table_sql(model)
File "/home/b/django/ENV/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 159, in table_sql
definition, extra_params = self.column_sql(model, field)
File "/home/b/django/ENV/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 212, in column_sql
db_params = field.db_parameters(connection=self.connection)
File "/home/b/django/ENV/lib/python3.7/site-packages/django/db/models/fields/related.py", line 971, in db_parameters
return {"type": self.db_type(connection), "check": self.db_check(connection)}
File "/home/b/django/ENV/lib/python3.7/site-packages/django/db/models/fields/related.py", line 968, in db_type
return self.target_field.rel_db_type(connection=connection)
File "/home/b/django/ENV/lib/python3.7/site-packages/django/db/models/fields/related.py", line 880, in target_field
return self.foreign_related_fields[0]
File "/home/b/django/ENV/lib/python3.7/site-packages/django/db/models/fields/related.py", line 632, in foreign_related_fields
return tuple(rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field)
File "/home/b/django/ENV/lib/python3.7/site-packages/django/db/models/fields/related.py", line 619, in related_fields
self._related_fields = self.resolve_related_fields()
File "/home/b/django/ENV/lib/python3.7/site-packages/django/db/models/fields/related.py", line 604, in resolve_related_fields
raise ValueError('Related model %r cannot be resolved' % self.remote_field.model)
ValueError: Related model 'polls.Car' cannot be resolved

为什么无法解析一个应用内的相关模型?

最佳答案

原因是migrations.CreateModel Body 的迁移在 CreateModel 之前存在于迁移文件中对于 Car ,更具体地说,它有

('car', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, parent_link=True, to='polls.Car', verbose_name='Машина')),

行在 Body CreateModel 之前 Car 模型已创建。

这可能是因为car字段 Bodyparent_link=True , 这表明应该建立到父模型的链接,因此该字段不会出现在当前(子)模型上,并且将此字段包含在迁移中是安全的。

但在您的情况下,这不是子模型,它不是从任何父模型继承的,因此使用 parent_link=True不需要。

最好的选择是删除parent_link=True ,删除之前创建的迁移文件并重新创建迁移。

另一种选择是简单地编辑迁移文件并为 Body 移动 CreateModel在 Car 的 CreateModel 之后, 但不推荐这样做。

关于django - 单个应用程序中的 ValueError ('Related model %r cannot be resolved' % self.remote_field.model),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59342669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com