2

我尝试运行 makemigrations 并在 migrate 之后不断收到此错误:

ValueError: Related model 'users.UserProfile' cannot be resolved

我试图做的是将UserProfile模型链接到 Django 自己的用户模型:

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

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    website = models.URLField(blank=True)
    bio = models.CharField(max_length=250, blank=True)
    full_name = models.CharField(max_length=250, blank=True)

竞赛”模型(如您在下面我安装的应用程序中所见)也使用用户模型,没有任何错误。

安装的应用程序如下所示:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users',
    'social.apps.django_app.default',
    'crispy_forms',
    'pages',
    'contests',
]

我的迁移文件0001_initial.py如下:

# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-30 15:45
from __future__ import unicode_literals

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

    operations = [
        migrations.CreateModel(
            name='UserProfile',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('website', models.URLField(blank=True)),
                ('bio', models.CharField(blank=True, max_length=250)),
                ('full_name', models.CharField(blank=True, max_length=250)),
                ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
    ]

其他注意事项:

  1. 我使用多个设置文件,但我安装的应用程序都在我的基本设置文件中,所以这应该不是问题。

  2. 我正在使用 Python Social Auth 创建管道并创建 UserProfile。(但这应该不会对数据库中模型的创建产生任何影响)

  3. 我什至删除了数据库并重新创建了它,但我仍然得到同样的错误。

提前致谢!!!:)

4

4 回答 4

14

我已经从其他应用程序中删除了所有迁移文件并运行 makemigrations 并再次迁移。

现在一切正常。

于 2016-12-30T16:27:56.090 回答
5

尝试为每个模型一个一个地运行迁移。

这样你就可以调试app你面临的问题

python manage.py migrate appmname

也许一个一个地运行迁移可能会有所帮助

于 2019-04-03T06:46:01.923 回答
3

我在创建自定义用户模型时遇到了类似的问题(如第一次迁移之前的文档中所写)。

class User(AbstractUser):
    pass

AUTH_USER_MODEL = 'account.user'

尝试迁移时,我遇到了“ValueError:无法解析相关模型'account.user'”。

在我第一次为新的自定义用户模型生成迁移后,它得到了解决。

保罗

于 2018-08-27T09:39:24.470 回答
1

您可以使用 cmd-shift-p 修复它或单击 View -> Command Palette 并运行命令 Python: Select Interpreter。只需在此处添加 virtualenv 目录即可享受。

于 2021-07-24T07:13:14.047 回答