Skip to content

Commit 96169d4

Browse files
committed
Work on netbox-community#2562, creating a hierarchy of prefixes
1 parent 0601619 commit 96169d4

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

netbox/ipam/querysets.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,33 @@
11
from django.db.models import QuerySet
2-
2+
from netaddr import IPNetwork
3+
from .constants import PREFIX_STATUS_CONTAINER
34

45
class PrefixQuerySet(QuerySet):
56

7+
def build_hierachy(self, limit=None):
8+
"""
9+
Iterate through a Queryset of Prefixes and build the parent-child relationships.
10+
"""
11+
queryset = self
12+
for p in queryset:
13+
p.parent = None
14+
p.depth = 0
15+
16+
for p in queryset:
17+
p.children = []
18+
for c in queryset:
19+
if (p.prefix != c.prefix and p.family == c.family and ((p.vrf is None and
20+
p.status == PREFIX_STATUS_CONTAINER) or p.vrf == c.vrf) and c.prefix.cidr in p.prefix.cidr):
21+
parent = c.parent
22+
if parent is None or parent.prefix in p.prefix:
23+
c.parent = p
24+
c.depth = p.depth + 1
25+
p.children.append(c)
26+
27+
return list(filter(lambda p: p.parent == None, self))
28+
29+
30+
631
def annotate_depth(self, limit=None):
732
"""
833
Iterate through a QuerySet of Prefixes and annotate the hierarchical level of each. While it would be preferable

0 commit comments

Comments
 (0)