querysets.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from collections import OrderedDict
  2. from django.db.models import Q, QuerySet
  3. class CustomFieldQueryset:
  4. """
  5. Annotate custom fields on objects within a QuerySet.
  6. """
  7. def __init__(self, queryset, custom_fields):
  8. self.queryset = queryset
  9. self.model = queryset.model
  10. self.custom_fields = custom_fields
  11. def __iter__(self):
  12. for obj in self.queryset:
  13. values_dict = {cfv.field_id: cfv.value for cfv in obj.custom_field_values.all()}
  14. obj.custom_fields = OrderedDict([(field, values_dict.get(field.pk)) for field in self.custom_fields])
  15. yield obj
  16. class ConfigContextQuerySet(QuerySet):
  17. def get_for_object(self, obj):
  18. """
  19. Return all applicable ConfigContexts for a given object. Only active ConfigContexts will be included.
  20. """
  21. # `device_role` for Device; `role` for VirtualMachine
  22. role = getattr(obj, 'device_role', None) or obj.role
  23. # Get the group of the assigned tenant, if any
  24. tenant_group = obj.tenant.group if obj.tenant else None
  25. # Match against the directly assigned region as well as any parent regions.
  26. region = getattr(obj.site, 'region', None)
  27. if region:
  28. regions = region.get_ancestors(include_self=True)
  29. else:
  30. regions = []
  31. return self.filter(
  32. Q(regions__in=regions) | Q(regions=None),
  33. Q(sites=obj.site) | Q(sites=None),
  34. Q(roles=role) | Q(roles=None),
  35. Q(platforms=obj.platform) | Q(platforms=None),
  36. Q(tenant_groups=tenant_group) | Q(tenant_groups=None),
  37. Q(tenants=obj.tenant) | Q(tenants=None),
  38. Q(tags__slug__in=obj.tags.slugs()) | Q(tags=None),
  39. is_active=True,
  40. ).order_by('weight', 'name')