From 96169d46be9b9512b6f2a15b100cbaf5cfb61110 Mon Sep 17 00:00:00 2001 From: Daniel Sheppard Date: Tue, 17 Sep 2019 15:37:50 -0500 Subject: [PATCH] Work on #2562, creating a hierarchy of prefixes --- netbox/ipam/querysets.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/netbox/ipam/querysets.py b/netbox/ipam/querysets.py index 9fd9bb6c142..425187dfae4 100644 --- a/netbox/ipam/querysets.py +++ b/netbox/ipam/querysets.py @@ -1,8 +1,33 @@ from django.db.models import QuerySet - +from netaddr import IPNetwork +from .constants import PREFIX_STATUS_CONTAINER class PrefixQuerySet(QuerySet): + def build_hierachy(self, limit=None): + """ + Iterate through a Queryset of Prefixes and build the parent-child relationships. + """ + queryset = self + for p in queryset: + p.parent = None + p.depth = 0 + + for p in queryset: + p.children = [] + for c in queryset: + if (p.prefix != c.prefix and p.family == c.family and ((p.vrf is None and + p.status == PREFIX_STATUS_CONTAINER) or p.vrf == c.vrf) and c.prefix.cidr in p.prefix.cidr): + parent = c.parent + if parent is None or parent.prefix in p.prefix: + c.parent = p + c.depth = p.depth + 1 + p.children.append(c) + + return list(filter(lambda p: p.parent == None, self)) + + + def annotate_depth(self, limit=None): """ Iterate through a QuerySet of Prefixes and annotate the hierarchical level of each. While it would be preferable