1 from django.db import models
2 from django.contrib.contenttypes.models import ContentType
3 from django.core.paginator import Paginator, EmptyPage
6 class ContentTypeLimiter(object):
8 return models.Q(pk__in=[])
10 def add_to_query(self, query, *args, **kwargs):
11 query.add_q(self.q_object(), *args, **kwargs)
14 class ContentTypeRegistryLimiter(ContentTypeLimiter):
18 def register_class(self, cls):
19 self.classes.append(cls)
21 def unregister_class(self, cls):
22 self.classes.remove(cls)
26 for cls in self.classes:
28 if issubclass(cls, models.Model):
29 if not cls._meta.abstract:
30 contenttype = ContentType.objects.get_for_model(cls)
31 contenttype_pks.append(contenttype.pk)
34 return models.Q(pk__in=contenttype_pks)
37 class ContentTypeSubclassLimiter(ContentTypeLimiter):
38 def __init__(self, cls, inclusive=False):
40 self.inclusive = inclusive
44 def handle_subclasses(cls):
45 for subclass in cls.__subclasses__():
47 if issubclass(subclass, models.Model):
48 if not subclass._meta.abstract:
49 if not self.inclusive and subclass is self.cls:
51 contenttype = ContentType.objects.get_for_model(subclass)
52 contenttype_pks.append(contenttype.pk)
53 handle_subclasses(subclass)
56 handle_subclasses(self.cls)
57 return models.Q(pk__in=contenttype_pks)
60 def fattr(*args, **kwargs):
61 def wrapper(function):
63 setattr(function, key, kwargs[key])
68 def paginate(objects, per_page=None, page_number=1):
70 Given a list of objects, return a (paginator, page, objects) tuple.
73 per_page = int(per_page)
74 except (TypeError, ValueError):
75 # Then either it wasn't set or it was set to an invalid value
76 paginator = page = None
78 # There also shouldn't be pagination if the list is too short. Try count()
79 # first - good chance it's a queryset, where count is more efficient.
81 if objects.count() <= per_page:
82 paginator = page = None
83 except AttributeError:
84 if len(objects) <= per_page:
85 paginator = page = None
88 return paginator, page, objects
92 paginator = Paginator(objects, per_page)
94 page_number = int(page_number)
99 page = paginator.page(page_number)
103 objects = page.object_list
105 return paginator, page, objects