【发布时间】:2016-01-05 05:28:03
【问题描述】:
在我的应用程序模型中,我需要一种链接Problems 和Solutions 的方法——每个Problem 可以有多个Solutions,并且给定的Solution 可以映射回多个Problems。
Solution 是一个抽象基类,因为Solutions 可以有很多变体。所以,我发现我需要一个映射表ProblemSolutionMapping,它使用GenericForeignKey 来容纳所有这些子类。但我试图弄清楚如何将类限制为Solutions 的子级,而不是整个应用程序中可用的所有类,这是目前正在发生的事情。
# 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')
问题是当我启动我的 Django 应用程序时,对ContentType.objects.filter(app_label=cls._meta.app_label) 的调用会引发错误:
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
不知道该怎么做——我尝试将映射表设置为相关模型文件中的最后一个(所有子类都在同一个文件中定义在其上方),但没有任何区别。 这是我必须进入管理表单的东西吗?还是在模型级别有其他方法可以做到这一点?
(Django 1.9,以防万一。)
提前感谢您的帮助!
【问题讨论】:
标签: django django-models