Django Admin:如何在父对象保存后才显示嵌套Inline?
问题:如何让django-nested-admin的子Inline在父对象保存后才显示?
环境版本
- Django 4.2
- django-nested-admin
- Python 3.10
模型代码
from django.db import models class Product(models.Model): name = models.CharField(max_length=255) class Component(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) name = models.CharField(max_length=255) class ComponentSetting(models.Model): component = models.ForeignKey(Component, on_delete=models.CASCADE) key = models.CharField(max_length=255) value = models.CharField(max_length=255)
Admin配置代码
from django.contrib import admin from nested_admin import NestedModelAdmin, NestedTabularInline class ComponentSettingInline(NestedTabularInline): model = ComponentSetting extra = 0 class ComponentInline(NestedTabularInline): model = Component extra = 0 inlines = [ComponentSettingInline] class ProductAdmin(NestedModelAdmin): inlines = [ComponentInline] admin.site.register(Product, ProductAdmin)
当前行为
- 编辑Product时可添加Component
- 添加新Component时,ComponentSetting inline立即可见
- 希望ComponentSetting inline仅在Component保存后才显示
期望行为
- 添加新Component时隐藏ComponentSetting inline
- 仅在Component保存后显示ComponentSetting inline
- 编辑已有Component时显示ComponentSetting inline
已尝试但无效的方案
- 重写
get_inlines():嵌套Inline仅在页面加载时调用一次,无法根据父对象是否已创建调整行为 - 使用
template属性返回空字符串或空模板 - 使用
has_add_permission和get_queryset - 检查父实例是否存在
以上方案均无法完全解决问题——要么Inline始终可见,要么始终隐藏。
求助
如何正确隐藏嵌套Inline(ComponentSetting),直到其父对象(Component)保存?
内容的提问来源于stack exchange,提问作者rastafalow
相关产品推荐
相关产品推荐

