Opened 14 months ago

Closed 13 months ago

Last modified 13 months ago

#22319 closed Bug (fixed)

ValueError: Related model cannot be resolved

Reported by: efrinut@… Owned by: nobody
Component: Migrations Version: master
Severity: Release blocker Keywords:
Cc: loic@…, RLion 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 (23)

comment:1 Changed 14 months ago by anonymous

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

It happens in django 1.7 beta 1

comment:2 Changed 14 months ago by melinath

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 Changed 14 months ago by melinath

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 Changed 14 months ago by melinath

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 Changed 14 months ago by melinath

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 Changed 14 months ago by anonymous

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 Changed 13 months ago by prairiedogg

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 Changed 13 months ago by anonymous

  • Severity changed from Normal to Release blocker

comment:9 Changed 13 months ago by loic84

@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 Changed 13 months ago by bmispelon

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

comment:11 Changed 13 months ago by loic84

  • 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 Changed 13 months ago by Tim Graham <timograham@…>

  • Resolution set to fixed
  • Status changed from new to closed

In 0fd51cf0bd31afb085d16476d5a54bedf4a1bc32:

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

comment:14 Changed 13 months ago by Tim Graham <timograham@…>

In 8e73d3a2c17bd3233d5c6c560dda73f74083f44f:

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

Backport of 0fd51cf0bd from master

comment:15 Changed 13 months ago by dbinetti@…

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 Changed 13 months ago by loic84

@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 Changed 13 months ago by dbinetti@…

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 Changed 13 months ago by maxwell.team@…

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 Changed 13 months ago by loic84

@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 Changed 13 months ago by RLion

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

https://github.com/TonyEight/minimal

comment:21 Changed 13 months ago by RLion

  • Cc RLion added

comment:22 Changed 13 months ago by charettes

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

comment:23 Changed 13 months ago by loic84

@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.

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