0
您好,我正在開發小型個人項目以獲得樂趣,我需要在模型中的所有模型中作爲選擇,我提供了一個函數來獲取所有模型名稱:模型列表作爲模型中的選項
def get_models():
choices = [ct.model_class().__name__ for ct in ContentType.objects.all()]
return choices
和我的模型:
class Action(models.Model):
model = models.CharField(max_length=70, null=False, blank=False, choices=lazy(get_models, list)())
act = models.CharField(max_length=3, null=False, blank=False, choices=ACTIONS_CHOICES)
description = models.TextField(max_length=400, null=True, blank=True)
count = models.IntegerField(null=False, blank=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.config
class Meta:
unique_together = (('model', 'act'),)
但是當我運行的代碼我有這樣的錯誤:
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
我試圖讓日E型不同的使用:
from django.apps import apps
models = apps.get_models()
但我不得不再次同樣的錯誤,我也明白的是,我試圖讓該機型之前的Django可以加載它們,我的問題是:有沒有什麼辦法解決這個問題?感謝
謝謝您的回答所有型號的選擇框,我試過對於第一種情況,我仍然有相同的錯誤(模型未加載),第二我有這個錯誤:'行動'對象沒有屬性'字段',btw我使用Django 1.10 – ddalu5
我誤讀你的問題,我以爲你是以一種形式來做這件事的。爲什麼不使用'ForeignKey'? 'content_type = models.ForeignKey(ContentType)' –
你是對的,你可以編輯你的答案,所以我可以將其標記爲已接受 – ddalu5