[英]Django polymorphic admin list views
我的 Django 代碼中有一個全局配置變量列表,其中有些是整數,有些是字符串。
我目前正在使用 django-polymorphic,因此基礎 model 具有名稱,子模型具有值。
例如:
class Configuration(PolymorphicModel):
name = models.CharField(max_length=128, unique=True)
def __str__(self):
return self.name
class ConfigurationInt(Configuration):
value = models.IntegerField(default=0)
def __str__(self):
return f'{self.name} = {self.value}'
class ConfigurationStr(Configuration):
value = models.CharField(max_length=256,default='')
def __str__(self):
return f'{self.name} = {self.value}'
然后將模型注冊到管理部分,如下所示:
@admin.register(Configuration)
class ConfigurationAdmin(PolymorphicParentModelAdmin):
list_display = ('__str__',)
child_models = (ConfigurationInt, ConfigurationStr)
@admin.register(ConfigurationInt)
class ConfigurationIntAdmin(PolymorphicChildModelAdmin):
base_model = ConfigurationInt
@admin.register(ConfigurationStr)
class ConfigurationStrAdmin(PolymorphicChildModelAdmin):
base_model = ConfigurationStr
不幸的是,__str__ 部分僅在“配置”的共享列表視圖中顯示基本 class 之一。 除了查看“ConfigurationInt”和“ConfigurationStr”的特定列表之外,無法以任何我能看到的方式訪問該值。
有什么方法可以將它們實際列出在一個不錯的列表中嗎?
Let's suppose I forget django-polymorphic and go with sparse data, such that each configuration has both an integer and a string, and some mechanism to state what it should be, like a type integer. 然后我可以在 __str__ 實現中顯示正確的數據,但是在編輯時,它會同時顯示兩者。 在像這樣的簡單示例中這可能沒問題,但是我也有明顯更復雜的模型,它們具有廣泛區分的領域,但在邏輯上都屬於單個列表。 那么在管理界面中是否有一種方法可以根據字段隱藏/顯示某些字段,例如在 list_display 和 list_editable 中?
長話短說,有沒有辦法在管理界面中真正正確地實現多態列表? 讓它在共享列表視圖中可編輯會很棒,但即使只是實際顯示信息,同時只能在對象本身或特定列表中進行編輯,也會很好。
埋在polymorphic.admin.parentadmin.py
的源代碼中是這樣的:
#: Whether the list should be polymorphic too, leave to ``False`` to optimize
polymorphic_list = False
...
def get_queryset(self, request):
# optimize the list display.
qs = super(PolymorphicParentModelAdmin, self).get_queryset(request)
if not self.polymorphic_list:
qs = qs.non_polymorphic()
return qs
哪種有意義。 看到您可能在那里顯示 20 個項目,因此默認嘗試優化它是有意義的。 否則該頁面超時的可能性太大。
無論如何,我認為設置:
polymorphic_list = True
有望為您解決此問題:)
實際上,它也在文檔中,(在實現細節下):
默認情況下,將在查詢集上調用 non_polymorphic() 方法,因此只會將 Parent model 提供給列表模板。 這是為了避免檢索子模型的性能損失。
這可以通過在父管理員上設置 polymorphic_list 屬性來控制。 將其設置為 True 將為列表模板提供子模型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.