In my application's models I need a way of linking Problems
and Solutions
-- every Problem
can have multiple Solutions
and a given Solution
can map back to multiple Problems
.
Solution
is an abstract base class, since there can be many varieties of Solutions
. So, I figured out I need a mapping table ProblemSolutionMapping
which uses a GenericForeignKey
to accommodate all those child classes. But I'm trying to figure out how to limit the classes to just the children of Solutions
and not all the classes available in the whole application, which is what is currently happening.
# Thanks to http://stackoverflow.com/a/23555691/1149759
class Solution(models.Model):
...
@classmethod
def get_subclasses(cls):
content_types = ContentType.objects.filter(app_label=cls._meta.app_label)
models = [ct.model_class() for ct in content_types]
return [model for model in models
if (model is not None and
issubclass(model, cls) and
model is not cls)]
class Meta:
abstract = True
class ProblemSolutionMapping(models.Model):
problem = models.ForeignKey(Problem)
content_type = models.ForeignKey(ContentType,
limit_choices_to=Solution.get_subclasses()) # <==== This is the issue
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
The issue is that when I start up my Django app, the call to ContentType.objects.filter(app_label=cls._meta.app_label)
throws the error:
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
Not sure what to do -- I tried making the mapping table the last one in the relevant models file (all the child classes are defined above it in the same file), but it made no difference. Is this something that I have to move into the admin form? Or is there some other way to do this at the model level?
(Django 1.9, in case it matters.)
Thanks in advance for your help!