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