在我的應用程序的模型,我需要連接和Solutions
的方式繼承CONTENTTYPES - 每Problem
可以有多個Solutions
和給定Solution
可以映射回多。Django的GenericForeignKey限制,從一個特定的抽象模型
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,如果它很重要。)
預先感謝您的幫助!
問題是,我不能靜態地將一個列表傳遞給'solution'子類的'limit_choice_to' bc。謝謝,不過。 – TAH