Opened 10 years ago

Closed 10 years ago

Last modified 4 years ago

#22319 closed Bug (fixed)

ValueError: Related model cannot be resolved

Reported by: efrinut@… Owned by: nobody
Component: Migrations Version: dev
Severity: Release blocker Keywords:
Cc: loic@…, TonyEight Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hey!

When I try to migrate comments model I get an error:

    raise ValueError('Related model %r cannot be resolved' % self.rel.to)
ValueError: Related model 'links.Link' cannot be resolved

It only happens for this model so when I remove Link fk everything passes smoothly

DJANGO_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'django.contrib.admindocs',
    'django.contrib.webdesign',
    'django.contrib.humanize',
    'django.contrib.sitemaps',
    'django.contrib.flatpages',
)

EXTERNAL_APPS = (
    'haystack',
    'storages',
    'pipeline',
    'endless_pagination',
    'easy_thumbnails',
    'mptt',
    'rest_framework',
    'crispy_forms',
    'crispy_forms_foundation',
    'taggit',
)

SITE_APPS = (
    'accounts',
    'links',
    'core',
    'images',
    'comments',
)

INSTALLED_APPS = DJANGO_APPS + EXTERNAL_APPS + SITE_APPS

# -*- coding: utf-8 -*-
from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings
from links.models import Link


class Comment(models.Model):
    link = models.ForeignKey(Link, null=True, blank=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=False)
    description = models.TextField(null=True, blank=False)
    parent = models.ForeignKey("self", null=True, blank=True)

    date_added = models.DateTimeField(auto_now_add=True, null=True)
    date_updated = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        verbose_name = u"Comment"
        verbose_name_plural = u"Comments"

    def get_absolute_url(self):
        return reverse("comment:detail", kwargs={'pk': self.pk})


# -*- coding: utf-8 -*-
from urlparse import urlparse
from django.core.urlresolvers import reverse
from django.db import models
from taggit.managers import TaggableManager
from .managers import ActiveManager
from django.conf import settings


class Link(models.Model):
    class Meta:
        verbose_name = u"Link"
        verbose_name_plural = u"Links"

    CONTENT = 1
    IMAGE = 2
    VIDEO = 3

    LINK_TYPES = (
        (CONTENT, u"content"),
        (IMAGE, u"image"),
        (VIDEO, u"video"),
    )

    title = models.CharField(max_length=255, null=True, blank=True)
    description = models.TextField(max_length=1000, null=True, blank=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=False)
    url = models.URLField(null=True, blank=False)
    domain = models.URLField(null=True, blank=False)
    date_added = models.DateTimeField(auto_now_add=True, null=True)
    date_updated = models.DateTimeField(auto_now=True, null=True)

    link_type = models.PositiveIntegerField(choices=LINK_TYPES, null=True, blank=False)
    classified = models.BooleanField(default=False)
    published = models.BooleanField(default=True)

    objects = models.Manager()
    active = ActiveManager()

    # tags = TaggableManager()

    def __unicode__(self):
        return u"{}".format(self.id)

    def get_domain(self):
        return u"{}".format(urlparse(self.url).netloc)

    def get_domain_url(self):
        url = urlparse(self.url)
        return u"{}://{}".format(url.scheme, url.netloc)

    def get_absolute_url(self):
        return reverse("link:detail", kwargs={'pk': self.pk})

    def get_vote_count(self):
        return 0

    def get_comment_count(self):
        return 0

Change History (27)

comment:1 by anonymous, 10 years ago

It happens in django 1.7 beta 1

comment:2 by Stephen Burrows, 10 years ago

I'm seeing this as well. Just tried to re-generate my migrations, and they won't run. I got it with auth.User, whether I specify it as 'auth.User' or by importing the model. It looks like the migration doesn't run do_pending_lookups for models from external apps, for some reason.

comment:3 by Stephen Burrows, 10 years ago

This *particular* bug starts showing up in https://github.com/django/django/commit/81f5408c7a16b8c79053950f05fe7a873506ca55 (git bisect) but I don't know whether that commit causes it or just uncovers it.

comment:4 by Stephen Burrows, 10 years ago

81f5408 is the first commit where the migrations that are autogenerated start exhibiting this behavior - but they have this behavior all the way back to 1.7a1, at the very least, once they've been generated. (I get different errors for my migrations that are generated *before* 81f5408, so I can't tell whether the generation is also wrong before that.)

comment:5 by Stephen Burrows, 10 years ago

This seems to be resolved (in the case where I'm getting it now - a rel to auth.Group) by adding a dependency to auth.__first__ - not sure why that wasn't automatically added. Also not sure why I was seeing this before, since swappable_dependency *was* present and seems to just be a shortcut to app_label.__first__

comment:6 by anonymous, 10 years ago

Whole error code just in case:

  Applying comments.0003_comment_link...Traceback (most recent call last):
  File "local_manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "D:\projekty\myinit\env\lib\site-packages\django\core\management\__init__
.py", line 427, in execute_from_command_line
    utility.execute()
  File "D:\projekty\myinit\env\lib\site-packages\django\core\management\__init__
.py", line 419, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:\projekty\myinit\env\lib\site-packages\django\core\management\base.py"
, line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "D:\projekty\myinit\env\lib\site-packages\django\core\management\base.py"
, line 337, in execute
    output = self.handle(*args, **options)
  File "D:\projekty\myinit\env\lib\site-packages\django\core\management\commands
\migrate.py", line 145, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "D:\projekty\myinit\env\lib\site-packages\django\db\migrations\executor.p
y", line 60, in migrate
    self.apply_migration(migration, fake=fake)
  File "D:\projekty\myinit\env\lib\site-packages\django\db\migrations\executor.p
y", line 94, in apply_migration
    migration.apply(project_state, schema_editor)
  File "D:\projekty\myinit\env\lib\site-packages\django\db\migrations\migration.
py", line 97, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, ne
w_state)
  File "D:\projekty\myinit\env\lib\site-packages\django\db\migrations\operations
\fields.py", line 36, in database_forwards
    field,
  File "D:\projekty\myinit\env\lib\site-packages\django\db\backends\schema.py",
line 378, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
  File "D:\projekty\myinit\env\lib\site-packages\django\db\backends\schema.py",
line 108, in column_sql
    db_params = field.db_parameters(connection=self.connection)
  File "D:\projekty\myinit\env\lib\site-packages\django\db\models\fields\related
.py", line 1749, in db_parameters
    return {"type": self.db_type(connection), "check": []}
  File "D:\projekty\myinit\env\lib\site-packages\django\db\models\fields\related
.py", line 1740, in db_type
    rel_field = self.related_field
  File "D:\projekty\myinit\env\lib\site-packages\django\db\models\fields\related
.py", line 1646, in related_field
    return self.foreign_related_fields[0]
  File "D:\projekty\myinit\env\lib\site-packages\django\db\models\fields\related
.py", line 1405, in foreign_related_fields
    return tuple(rhs_field for lhs_field, rhs_field in self.related_fields)
  File "D:\projekty\myinit\env\lib\site-packages\django\db\models\fields\related
.py", line 1392, in related_fields
    self._related_fields = self.resolve_related_fields()
  File "D:\projekty\myinit\env\lib\site-packages\django\db\models\fields\related
.py", line 1377, in resolve_related_fields
    raise ValueError('Related model %r cannot be resolved' % self.rel.to)
ValueError: Related model 'links.Link' cannot be resolved

comment:7 by prairiedogg, 10 years ago

This is also happening to me in a simple and reproducible case where I add a foreign key on a model to ContentType, makemigrations generates the migration just fine, but migrateraises the same ValueError: Related model 'contenttypes.ContentType' cannot be resolved error.

comment:8 by anonymous, 10 years ago

Severity: NormalRelease blocker

comment:9 by loic84, 10 years ago

@prairiedogg, any chance you could reproduce with a minimal project that has a FK to contenttypes? I haven't managed to reproduce yet.

comment:10 by Baptiste Mispelon, 10 years ago

I just closed #22332 as a duplicate and it had a minimal project for reproducing.

comment:11 by loic84, 10 years ago

Cc: loic@… added
Has patch: set

I came up with this patch, does it solve your issues?

https://github.com/loic/django/compare/ticket22332

comment:13 by Tim Graham <timograham@…>, 10 years ago

Resolution: fixed
Status: newclosed

In 0fd51cf0bd31afb085d16476d5a54bedf4a1bc32:

Fixed #22319 -- Fixed migration external dependencies when there are internal dependencies.

comment:14 by Tim Graham <timograham@…>, 10 years ago

In 8e73d3a2c17bd3233d5c6c560dda73f74083f44f:

[1.7.x] Fixed #22319 -- Fixed migration external dependencies when there are internal dependencies.

Backport of 0fd51cf0bd from master

comment:15 by dbinetti@…, 10 years ago

Complete n00b here, so I'm not sure if I'm following protocol, but this fix does not work for me. How do I go about reporting it? I'm not even sure how to doc the steps to reproduce...

comment:16 by loic84, 10 years ago

@dbinetti, did you delete the existing migrations? This patch fixes the generation of migrations, but if your migration is already generated, it's not going to help.

comment:17 by dbinetti@…, 10 years ago

so sorry for the late response! i assumed i'd be notified of followups.

as it turns out I changed my model schema, and have not experienced this since. so perhaps it worked, perhaps some other solution, but in any case no problems since.

thanks!

comment:18 by maxwell.team@…, 10 years ago

I've same problem with my

content_type = models.ForeignKey(ContentType)

changing to

content_type = models.ForeignKey(ContentType, null=True, blank=True)

I've tried to apply patch – but the error remains:

ValueError: Related model 'contenttypes.ContentType' cannot be resolved

comment:19 by loic84, 10 years ago

@maxwell.team did you try to remove the faulty migration after applying the patch, then running makemigrations and finally running migrate again?

Also you may want to try the master version of django on github, since this patch has been merged already.

Feel free to ping me on the #django-dev IRC channel (loic84).

comment:20 by TonyEight, 10 years ago

It seems like there's another dependancy problem, occuring with auth.User.

https://github.com/TonyEight/minimal

comment:21 by TonyEight, 10 years ago

Cc: TonyEight added

comment:22 by Simon Charette, 10 years ago

@RLion the auth.User dependency problem is tracked in #22485.

comment:23 by loic84, 10 years ago

@charettes, interestingly, it's not the same error, but rather ValueError: Lookup failed for model referenced by field auth.Permission.content_type: contenttypes.ContentType.

I find that generating migrations for d.c.contenttypes then d.c.auth fixes the problem up to the point of #22485.

comment:24 by Sudhanshu Mishra, 8 years ago

I think this bug is still there in Django 1.9.3. Yesterday, I just added null=True, blank=True to a ForeignKey field and executed python manage.py migrate after makemigrations and it refused to migrate stating the same error.

comment:25 by Tim Graham, 8 years ago

Please open a new ticket with steps to reproduce the problem.

comment:26 by rvernica, 4 years ago

I ran into this error when using manage.py sqlmigrate on Django 2.2.7

comment:27 by rvernica, 4 years ago

I was able to move past this by adding the following to the dependencies field in the Migration:

class Migration(migrations.Migration):

  dependencies = [
    ('NAME_OF_RELATED_APP', 'LAST_MIGRATION_IN_THAT_APP'),
    ...
  ]

Now sqlmigrate works as expected.

After looking around it seems that this problem has been encountered before and this solution worked in the past.

Note: See TracTickets for help on using tickets.
Back to Top