Opened 3 years ago

Closed 3 years ago

#32851 closed Bug (invalid)

GenericRelation inherited from Abstract model in different app fails to generate migration

Reported by: Foucauld Degeorges Owned by: nobody
Component: Uncategorized Version: 2.2
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I'm trying to create a new model in a new app B, inheriting from an abstract model in app A:

# app_b/models.py
from app_a.models import Foo

class ConcreteModel(Foo):
   pass

Foo has a GenericRelation to another model of app A:

# app_a/models.py
from django.contrib.contenttypes.fields import GenericRelation

class Foo(models.Model):
    class Meta:
        abstract = True
    
    some_relation = GenericRelation(
        "Bar",
        content_type_field="foo_type",
        object_id_field="foo_id"
    )

class Bar(models.Model):
    # whatever

Generation of the initial migration of app B fails with the following SystemCheck errors:

<function GenericRelation.contribute_to_class.<locals>.make_generic_foreign_order_accessors at 0x7fa2a6747c80>: (models.E022) <function GenericRelation.contribute_to_class.<locals>.make_generic_foreign_order_accessors at 0x7fa2a6747c80> contains a lazy reference to app_b.bar, but app 'app_b' doesn't provide model 'bar'.
app_b.ConcreteModel.some_relation: (fields.E307) The field app_b.ConcreteModel.some_relation was declared with a lazy reference to 'app_b.bar', but app 'app_b' doesn't provide model 'bar'.

Indeed, app_b does not provide Bar, app_a does.

I tried explicitly mentioning app_a in the GenericRelation:

some_relation = GenericRelation(
    "app_a.Bar",
    content_type_field="foo_type",
    object_id_field="foo_id"
)

but this does not generate a migration for app_a, nor does it fix the problem.

Change History (1)

comment:1 by Carlton Gibson, 3 years ago

Resolution: invalid
Status: newclosed

From the ForeignKey docs:

To refer to models defined in another application, you can explicitly specify a model with the full application label.

So, despite you saying you tried this, this works:

    some_relation = GenericRelation(
        "app_a.Bar",
        content_type_field="foo_type",
        object_id_field="foo_id"
    )

As does making Bar a non-lazy reference:

    some_relation = GenericRelation(
        Bar,
        content_type_field="foo_type",
        object_id_field="foo_id"
    )

Both of these approaches correctly generate the correct migrations. Please see TicketClosingReasons/UseSupportChannels if you require further assistance.

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