add nick
[laas.git] / src / dashboard / utils.py
1 ##############################################################################
2 # Copyright (c) 2020 Parker Berberian and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10 from django.core.exceptions import (ObjectDoesNotExist, MultipleObjectsReturned)
11
12
13 class AbstractModelQuery():
14     """
15     This is a class made for querying abstract models.
16
17     This class is itself abstract. create subclasses to
18     query your own abstract models.
19     """
20
21     model_list = []
22
23     @classmethod
24     def filter(cls, *args, **kwargs):
25         """
26         Query all concrete model classes.
27
28         Iterates over the model list and returns a list of all
29         matching models from the classes given.
30         Filter queries are given here as normal and are passed into the Django ORM
31         for each concrete model
32         """
33         result = []
34         for model in cls.model_list:
35             result += list(model.objects.filter(*args, **kwargs))
36
37         return result
38
39     @classmethod
40     def get(cls, *args, **kwargs):
41         """
42         Gets a single matching resource
43         Throws ObjectDoesNotExist if none found matching, or MultipleObjectsReturned if
44         the query does not narrow to a single object
45         """
46         try:
47             ls = cls.filter(*args, **kwargs)
48             if len(ls) > 1:
49                 raise MultipleObjectsReturned()
50             return cls.filter(*args, **kwargs)[0]
51         except IndexError:
52             raise ObjectDoesNotExist()