如何根据外表中的值为django TabularInline动态设置max_num?

 手机用户2602907455 发布于 2023-02-04 15:34

考虑以下数据模型:

class Model(models.Model):
    """A specific model of managed network switch. """
    name = models.CharField(max_length=20)
    port_count = models.IntegerField()

class Switch(models.Model):
    """A deployed instance of a managed network switch."""
    model = models.ForeignKey(Model)
    name = models.CharField(max_length=14)

class Port(models.Model):
    """A port on a deployed instance of a managed network switch."""
    switch = models.ForeignKey(Switch)
    number = models.IntegerField()
    ip_address = models.GenericIPAddressField(
        protocol='IPv4', verbose_name='IP address')
    netmask = models.GenericIPAddressField(protocol='IPv4')
    vlan = models.IntegerField(verbose_name='VLAN')

我想要我的管理页面,以便在Switch下内联端口.所以我有:

class PortInLineAdmin(admin.TabularInline):
    model = Port
    extra = 8
    max_num = 48

class SwitchAdmin(admin.ModelAdmin):
    inlines = [PortInLineAdmin]

这非常接近我想要实现的目标.但是,我真正想要的是PortInLineAdmin.max_num在运行时将动态设置为 Model.port_count我正在编辑的交换机而不是在48处进行硬编码,如上所示.我如何实现这一目标?

1 个回答
  • 您可以覆盖get_max_numPortInLineAdmin:

    class PortInLineAdmin(admin.TabularInline):
        model = Port
        extra = 8
    
        def get_max_num(self, request, obj=None, **kwargs):
            return obj.model.port_count
    

    在Django 1.5中你需要一个不同的技巧:

    class PortInLineAdmin(admin.TabularInline):
        model = Port
        extra = 8
    
        def get_formset(self, request, obj=None, **kwargs):
            self.max_num = obj.model.port_count
            return super(PortInLineAdmin, self).get_formset(request, obj, **kwargs)
    

    2023-02-04 15:38 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有