-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanagers.py
52 lines (39 loc) · 1.59 KB
/
managers.py
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
from django.db import models
from django.core.exceptions import ObjectDoesNotExist
class QuerySetManager(models.Manager):
# http://docs.djangoproject.com/en/dev/topics/db/managers/#using-managers-for-related-object-access
use_for_related_fields = True
def __init__(self, qs_class=models.query.QuerySet):
self.queryset_class = qs_class
super(QuerySetManager, self).__init__()
def get_query_set(self):
return self.queryset_class(self.model)
def __getattr__(self, attr, *args):
try:
return getattr(self.__class__, attr, *args)
except AttributeError:
return getattr(self.get_query_set(), attr, *args)
class QuerySet(models.query.QuerySet):
"""Base QuerySet class for adding custom methods that are made
available on both the manager and subsequent cloned QuerySets"""
@classmethod
def as_manager(cls, ManagerClass=QuerySetManager):
return ManagerClass(cls)
class BetterQuerySet(QuerySet):
"""
This QuerySet set allows for one to do a lot of common things.
It's intended to be a replacement for the default QuerySet manager.
"""
def get(self, **kwargs):
"""
Like a regular get, except one can pass in a default value as
a second kwarg.
"""
if len(kwargs) > 1 and 'default' in kwargs:
d = kwargs.pop('default')
try:
#return None
return super(BetterQuerySet, self).get(**kwargs)
except ObjectDoesNotExist:
return d
return super(BetterQuerySet, self).get(**kwargs)