Ad

How To Get Masklen From Model

- 1 answer

the model as below to store the ip address in postgres.

from django.db import models
from netfields import InetAddressField, CidrAddressField, NetManager

class TestModel(models.Model):
    client_ip = InetAddressField(default='0.0.0.0/0', store_prefix_length=True)

I want to get the IP masklength directly through the model. but I can't find a attribute correspondig to postgresql inet masklen https://www.postgresql.org/docs/9.4/functions-net.html

Ad

Answer

If you want to get the masklength from single object you can define your model like:

from ipaddress import ip_interface

from django.db import models
from netfields import InetAddressField, CidrAddressField, NetManager

class TestModel(models.Model):
    client_ip = InetAddressField(default=ip_interface('0.0.0.0/0'), store_prefix_length=True)

    @property
    def masklength(self):
        return self.client_ip.network.prefixlen

Example:

obj = TestModel(client_ip=ip_interface('192.168.1.0/24'))
obj.masklength # 24

Note that ipaddress is builtin in Python 3.3+, so if you are using older version you will have to install this

Ad
source: stackoverflow.com
Ad