2019-05-16 19:45:36 -04:00
|
|
|
from collections import OrderedDict
|
|
|
|
|
2018-06-28 13:48:12 -04:00
|
|
|
from django.db.models import Q, QuerySet
|
|
|
|
|
|
|
|
|
2019-05-16 19:45:36 -04:00
|
|
|
class CustomFieldQueryset:
|
|
|
|
"""
|
|
|
|
Annotate custom fields on objects within a QuerySet.
|
|
|
|
"""
|
|
|
|
def __init__(self, queryset, custom_fields):
|
|
|
|
self.queryset = queryset
|
|
|
|
self.model = queryset.model
|
|
|
|
self.custom_fields = custom_fields
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
for obj in self.queryset:
|
|
|
|
values_dict = {cfv.field_id: cfv.value for cfv in obj.custom_field_values.all()}
|
|
|
|
obj.custom_fields = OrderedDict([(field, values_dict.get(field.pk)) for field in self.custom_fields])
|
|
|
|
yield obj
|
|
|
|
|
|
|
|
|
2018-06-28 13:48:12 -04:00
|
|
|
class ConfigContextQuerySet(QuerySet):
|
|
|
|
|
|
|
|
def get_for_object(self, obj):
|
|
|
|
"""
|
|
|
|
Return all applicable ConfigContexts for a given object. Only active ConfigContexts will be included.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# `device_role` for Device; `role` for VirtualMachine
|
|
|
|
role = getattr(obj, 'device_role', None) or obj.role
|
|
|
|
|
2020-01-26 10:53:58 +00:00
|
|
|
# Virtualization cluster for VirtualMachine
|
|
|
|
cluster = getattr(obj, 'cluster', None)
|
|
|
|
cluster_group = getattr(cluster, 'group', None)
|
|
|
|
|
2018-07-27 15:47:29 -04:00
|
|
|
# Get the group of the assigned tenant, if any
|
|
|
|
tenant_group = obj.tenant.group if obj.tenant else None
|
|
|
|
|
2018-07-27 15:10:43 -04:00
|
|
|
# Match against the directly assigned region as well as any parent regions.
|
|
|
|
region = getattr(obj.site, 'region', None)
|
|
|
|
if region:
|
|
|
|
regions = region.get_ancestors(include_self=True)
|
|
|
|
else:
|
|
|
|
regions = []
|
|
|
|
|
2018-06-28 13:48:12 -04:00
|
|
|
return self.filter(
|
2018-07-27 15:10:43 -04:00
|
|
|
Q(regions__in=regions) | Q(regions=None),
|
2018-06-28 13:48:12 -04:00
|
|
|
Q(sites=obj.site) | Q(sites=None),
|
|
|
|
Q(roles=role) | Q(roles=None),
|
|
|
|
Q(platforms=obj.platform) | Q(platforms=None),
|
2020-01-26 10:53:58 +00:00
|
|
|
Q(cluster_groups=cluster_group) | Q(cluster_groups=None),
|
|
|
|
Q(clusters=cluster) | Q(clusters=None),
|
2018-07-27 15:47:29 -04:00
|
|
|
Q(tenant_groups=tenant_group) | Q(tenant_groups=None),
|
|
|
|
Q(tenants=obj.tenant) | Q(tenants=None),
|
2019-12-11 15:55:33 -05:00
|
|
|
Q(tags__slug__in=obj.tags.slugs()) | Q(tags=None),
|
2018-06-28 13:48:12 -04:00
|
|
|
is_active=True,
|
|
|
|
).order_by('weight', 'name')
|