-
-
Notifications
You must be signed in to change notification settings - Fork 275
/
managers.py
80 lines (64 loc) · 2.84 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# -*- coding: utf-8 -*-
"""
The manager class for use in the models.
"""
from __future__ import unicode_literals
import warnings
import django
from django.db import models
from polymorphic.query import PolymorphicQuerySet
try:
from django.utils.six import python_2_unicode_compatible
except ImportError:
from django.utils.encoding import python_2_unicode_compatible # Django 1.5
__all__ = (
'PolymorphicManager',
'PolymorphicQuerySet',
)
@python_2_unicode_compatible
class PolymorphicManager(models.Manager):
"""
Manager for PolymorphicModel
Usually not explicitly needed, except if a custom manager or
a custom queryset class is to be used.
"""
# Tell Django that related fields also need to use this manager:
use_for_related_fields = True
queryset_class = PolymorphicQuerySet
def __init__(self, queryset_class=None, *args, **kwrags):
# Up till polymorphic 0.4, the queryset class could be specified as parameter to __init__.
# However, this doesn't work for related managers which instantiate a new version of this class.
# Hence, for custom managers the new default is using the 'queryset_class' attribute at class level instead.
if queryset_class:
warnings.warn("Using PolymorphicManager(queryset_class=..) is deprecated; override the queryset_class attribute instead", DeprecationWarning)
# For backwards compatibility, still allow the parameter:
self.queryset_class = queryset_class
super(PolymorphicManager, self).__init__(*args, **kwrags)
def get_queryset(self):
if django.VERSION >= (1, 7):
qs = self.queryset_class(self.model, using=self._db, hints=self._hints)
else:
qs = self.queryset_class(self.model, using=self._db)
if self.model._meta.proxy:
qs = qs.instance_of(self.model)
return qs
# For Django 1.5
if django.VERSION < (1, 7):
get_query_set = get_queryset
def __str__(self):
return '%s (PolymorphicManager) using %s' % (self.__class__.__name__, self.queryset_class.__name__)
# Proxied methods
def non_polymorphic(self):
return self.all().non_polymorphic()
def instance_of(self, *args):
return self.all().instance_of(*args)
def not_instance_of(self, *args):
return self.all().not_instance_of(*args)
def get_real_instances(self, base_result_objects=None):
return self.all().get_real_instances(base_result_objects=base_result_objects)
if django.VERSION >= (1, 7):
@classmethod
def from_queryset(cls, queryset_class, class_name=None):
manager = super(PolymorphicManager, cls).from_queryset(queryset_class, class_name=class_name)
manager.queryset_class = queryset_class # also set our version, Django uses _queryset_class
return manager