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

如何根据外部表中的值动态设置django Tablerinline的max_num?,django,django-admin,Django,Django Admin,考虑以下数据模型: 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

考虑以下数据模型:

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')
我希望我的管理页面,以便端口内联在交换机下。因此,我:

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

class SwitchAdmin(admin.ModelAdmin):
    inlines = [PortInLineAdmin]
这与我想要实现的目标非常接近。然而,我真正想要的是什么 是在运行时将
PortInLineAdmin.max_num
动态设置为
我正在编辑而不是硬编码的交换机的Model.port\u count

如上图所示,在48。如何实现这一点?

您可以在
PortInLineAdmin
中覆盖
get\u max\u num

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 YourModelLin(TabularLin):
model = YourModel
....

def get_max_num(self, request, obj=None, **kwargs):
    return obj.yourmodel_set.count() + 1

它在django 2.2:)

中工作得非常完美,看起来很棒,但我无法让它工作,现在我明白了原因。“在Django 1.6中新增”。我需要一个解决方案,将在1.5.1工作真棒!从阅读文档中,我想可能会涉及到表单集,但我是Django的新手,有点迷路了。您的解决方案非常有效。我还没有测试第一个(v1.6版),但它是有意义的。两者都非常清楚和简单。谢谢
class YourModelLin(TabularLin):
model = YourModel
....

def get_max_num(self, request, obj=None, **kwargs):
    return obj.yourmodel_set.count() + 1