基于模型的 Django Admin 条件显示内联 属性

Django Admin conditional display inlines based on models property

我有带字段的市场模型:

class VacationEvent(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    process_fba = models.BooleanField(default=True)

    @property
    def has_amazon_fba_vacation(self):
        return hasattr(self, 'amazon_fba_vacation')

并且在 admin.py 中:

class FBAInline(admin.StackedInline):
    model = AmazonFBAVacation
    can_delete = False
    verbose_name_plural = 'amazon fba vacation'
    fk_name = 'event'

我需要在 creating\updating VacationEventAdmin 时有条件地显示 FBAInline class。 list_filter 显示 true\false 字段的 "process_fba" 值,所以如果它是 true - FBAInline 应该显示:

@admin.register(VacationEvent)
class VacationEventAdmin(admin.ModelAdmin):
    inlines = []
    list_display = ('id', 'user', 'holiday_name', 'start_date', 'end_date', 'process_fba', 'process_fbm', 'process_walmart', 'process_ebay')
    list_filter = ['process_fba', 'process_fbm', 'process_walmart', 'process_ebay', 'status',]
    search_fields = ['holiday_name', 'user__username']

# if VacationEvent.process_fba and VacationEvent.has_amazon_fba_vacation:
#     inlines.append(FBAInline)

# try:
#     getattr(VacationEvent, 'process_fba')
# except AttributeError:
#     print "doesn't"
# else:
#     inlines.append(FBAInline)

我尝试获取 attr 但不明白如何比较管理员的字段值。感谢您的帮助。

覆盖get_formsets_with_inlines方法

get_formsets_with_inlines(self, request, obj=None):
    for inline in self.get_inline_instances(request, obj):
        if obj and obj.has_amazon_fba_vacation:
            yield inline.get_formset(request, obj), inline