Automatically count elements in ManyToMany Django model

I'm looking for a way to count a number of "reserved" objects inside of "IPSubnetAllocation" class that I've created (if at all possible?).

Effectively what I'm doing is allocating smaller IP subnets within a larger block "IPBlockAllocation" e.g:

Parent Prefix:


Child Prefix:

  • Omitted...
  • 192.168.254/31

I can assign a child prefix to an interface (any network device) and set it's reserved status to True. This means it's no longer available for reservation (this logic is outside of scope). What I would like however is to automatically increment / decrement count of "subnets_reserved" of the "IPBlockAllocation".

class IPSubnetAllocation(models.Model):
    parent_prefix = models.ForeignKey(
        'IPBlockAllocation', null=True, on_delete=models.CASCADE
    subnet = models.CharField(
        blank=True, null=True, unique=True, max_length=15)
    assigned_interface = models.ForeignKey(
        DeviceInterfaces, null=True, on_delete=models.CASCADE)
    reserved = models.BooleanField(default=False)
    role = models.CharField(choices=IP_BLOCK_ROLE,
                            default='Select', max_length=10)

class IPBlockAllocation(models.Model):
    name = models.CharField(unique=True, max_length=255)
    prefix = models.GenericIPAddressField(
        blank=True, null=True, unique=True, validators=[validate_ipv4_address])
    mask = models.IntegerField(choices=SUBNET_MASK, default='Select')
    subnets = models.ManyToManyField(IPSubnetAllocation, blank=True)
    subnets_count = models.IntegerField(blank=True, null=True)
    subnets_reserved = models.IntegerField(default=0, blank=True, null=True)
    role = models.CharField(choices=IP_BLOCK_ROLE,
                            default='Select', max_length=10)
Back to Top