如何从国防部得到蒙克伦

2024-04-20 03:02:49 发布

您现在位置:Python中文网/ 问答频道 /正文

在postgres中存储ip地址的模型如下。你知道吗

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)

我想直接通过模型得到IP掩蔽长度。 但我找不到与postgresql inet masklen对应的属性 https://www.postgresql.org/docs/9.4/functions-net.html


Tags: djangofrom模型importipdbmodelspostgresql
2条回答

您可以创建自己的^{}将此函数添加到项目中:

from django.db.models import IntegerField, Func


class MaskLen(Func):
    function = 'MASKLEN'

    def __init__(self, output_field=None, **extra):
        if output_field is None:
            output_field = IntegerField()
        super(TransactionNow, self).__init__(output_field=output_field, **extra)

然后按如下方式使用:qs.annotate(mask_length=MaskLen('client_ip'))

如果要从单个对象获取遮罩长度,可以定义模型,如下所示:

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

示例:

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

请注意,^{}是在python3.3+中内置的,因此如果您使用的是旧版本,则必须安装this

相关问题 更多 >