diff --git a/netbox/netbox/models/features.py b/netbox/netbox/models/features.py index a972277705c..e58037b8546 100644 --- a/netbox/netbox/models/features.py +++ b/netbox/netbox/models/features.py @@ -5,6 +5,7 @@ from django.contrib.contenttypes.fields import GenericRelation from django.core.validators import ValidationError from django.db import models +from django.db.models import Q from django.utils import timezone from django.utils.translation import gettext_lazy as _ from taggit.managers import TaggableManager @@ -363,6 +364,26 @@ class ContactsMixin(models.Model): class Meta: abstract = True + def get_contacts(self, inherited=True): + """ + Return a `QuerySet` matching all contacts assigned to this object. + + :param inherited: If `True`, inherited contacts from parent objects are included. + """ + from tenancy.models import ContactAssignment + from . import NestedGroupModel + + filter = Q( + object_type=ObjectType.objects.get_for_model(self), + object_id__in=( + self.get_ancestors(include_self=True) + if (isinstance(self, NestedGroupModel) and inherited) + else [self.pk] + ), + ) + + return ContactAssignment.objects.filter(filter) + class BookmarksMixin(models.Model): """ diff --git a/netbox/tenancy/views.py b/netbox/tenancy/views.py index 0988d2e6542..3b5029bd793 100644 --- a/netbox/tenancy/views.py +++ b/netbox/tenancy/views.py @@ -17,25 +17,13 @@ class ObjectContactsView(generic.ObjectChildrenView): template_name = 'tenancy/object_contacts.html' tab = ViewTab( label=_('Contacts'), - badge=lambda obj: obj.contacts.count(), + badge=lambda obj: obj.get_contacts().count(), permission='tenancy.view_contactassignment', weight=5000 ) def get_children(self, request, parent): - return ContactAssignment.objects.restrict(request.user, 'view').filter( - object_type=ContentType.objects.get_for_model(parent), - object_id=parent.pk - ).order_by('priority', 'contact', 'role') - - def get_table(self, *args, **kwargs): - table = super().get_table(*args, **kwargs) - - # Hide object columns - table.columns.hide('object_type') - table.columns.hide('object') - - return table + return parent.get_contacts().restrict(request.user, 'view').order_by('priority', 'contact', 'role') #