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_queryset(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):
40 return self.intermediary_table_model.objects.get_related(
43 return self.intermediary_table_model.objects.get_related(
46 def with_all(self, tags, queryset=None):
48 return self.intermediary_table_model.objects.get_by_model(self.model, tags)
50 return self.intermediary_table_model.objects.get_by_model(queryset, tags)
52 def with_any(self, tags, queryset=None):
54 return self.intermediary_table_model.objects.get_union_by_model(self.model, tags)
56 return self.intermediary_table_model.objects.get_union_by_model(queryset, tags)
59 class TagDescriptor(object):
61 A descriptor which provides access to a ``ModelTagManager`` for
62 model classes and simple retrieval, updating and deletion of tags
65 def __init__(self, tag_model):
66 self.tag_model = tag_model
68 def __get__(self, instance, owner):
70 tag_manager = ModelTagManager(self.tag_model)
71 tag_manager.model = owner
74 return self.tag_model.objects.get_for_object(instance)
76 def __set__(self, instance, value):
77 self.tag_model.objects.update_tags(instance, value)
79 def __del__(self, instance):
80 self.tag_model.objects.update_tags(instance, [])