querysets.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. from __future__ import unicode_literals
  2. from django.db.models import Q, QuerySet
  3. class ConfigContextQuerySet(QuerySet):
  4. def get_for_object(self, obj):
  5. """
  6. Return all applicable ConfigContexts for a given object. Only active ConfigContexts will be included.
  7. """
  8. # `device_role` for Device; `role` for VirtualMachine
  9. role = getattr(obj, 'device_role', None) or obj.role
  10. # Get the group of the assigned tenant, if any
  11. tenant_group = obj.tenant.group if obj.tenant else None
  12. # Match against the directly assigned region as well as any parent regions.
  13. region = getattr(obj.site, 'region', None)
  14. if region:
  15. regions = region.get_ancestors(include_self=True)
  16. else:
  17. regions = []
  18. return self.filter(
  19. Q(regions__in=regions) | Q(regions=None),
  20. Q(sites=obj.site) | Q(sites=None),
  21. Q(roles=role) | Q(roles=None),
  22. Q(platforms=obj.platform) | Q(platforms=None),
  23. Q(tenant_groups=tenant_group) | Q(tenant_groups=None),
  24. Q(tenants=obj.tenant) | Q(tenants=None),
  25. is_active=True,
  26. ).order_by('weight', 'name')