1 # -*- coding: utf-8 -*-
3 Custom managers for Django models registered with the tagging
6 from django.contrib.contenttypes.models import ContentType
7 from django.db import models
10 class ModelTagManager(models.Manager):
12 A manager for retrieving tags for a particular model.
14 def __init__(self, tag_model):
15 super(ModelTagManager, self).__init__()
16 self.tag_model = tag_model
18 def get_query_set(self):
19 content_type = ContentType.objects.get_for_model(self.model)
20 return self.tag_model.objects.filter(
21 items__content_type__pk=content_type.pk).distinct()
23 def related(self, tags, *args, **kwargs):
24 return self.tag_model.objects.related_for_model(tags, self.model, *args, **kwargs)
26 def usage(self, *args, **kwargs):
27 return self.tag_model.objects.usage_for_model(self.model, *args, **kwargs)
30 class ModelTaggedItemManager(models.Manager):
32 A manager for retrieving model instances based on their tags.
34 def __init__(self, tag_model):
35 super(ModelTaggedItemManager, self).__init__()
36 self.intermediary_table_model = tag_model.objects.intermediary_table_model
38 def related_to(self, obj, queryset=None, num=None):
40 return self.intermediary_table_model.objects.get_related(obj, self.model, num=num)
42 return self.intermediary_table_model.objects.get_related(obj, queryset, num=num)
44 def with_all(self, tags, queryset=None):
46 return self.intermediary_table_model.objects.get_by_model(self.model, tags)
48 return self.intermediary_table_model.objects.get_by_model(queryset, tags)
50 def with_any(self, tags, queryset=None):
52 return self.intermediary_table_model.objects.get_union_by_model(self.model, tags)
54 return self.intermediary_table_model.objects.get_union_by_model(queryset, tags)
57 class TagDescriptor(object):
59 A descriptor which provides access to a ``ModelTagManager`` for
60 model classes and simple retrieval, updating and deletion of tags
63 def __init__(self, tag_model):
64 self.tag_model = tag_model
66 def __get__(self, instance, owner):
68 tag_manager = ModelTagManager(self.tag_model)
69 tag_manager.model = owner
72 return self.tag_model.objects.get_for_object(instance)
74 def __set__(self, instance, value):
75 self.tag_model.objects.update_tags(instance, value)
77 def __del__(self, instance):
78 self.tag_model.objects.update_tags(instance, [])