1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
5 Custom managers for Django models registered with the tagging
8 from django.contrib.contenttypes.models import ContentType
9 from django.db import models
12 class ModelTagManager(models.Manager):
14 A manager for retrieving tags for a particular model.
16 def __init__(self, tag_model):
17 super(ModelTagManager, self).__init__()
18 self.tag_model = tag_model
20 def get_queryset(self):
21 content_type = ContentType.objects.get_for_model(self.model)
22 return self.tag_model.objects.filter(
23 items__content_type__pk=content_type.pk).distinct()
25 def related(self, tags, *args, **kwargs):
26 return self.tag_model.objects.related_for_model(tags, self.model, *args, **kwargs)
28 def usage(self, *args, **kwargs):
29 return self.tag_model.objects.usage_for_model(self.model, *args, **kwargs)
32 class ModelTaggedItemManager(models.Manager):
34 A manager for retrieving model instances based on their tags.
36 def __init__(self, tag_model):
37 super(ModelTaggedItemManager, self).__init__()
38 self.intermediary_table_model = tag_model.objects.intermediary_table_model
40 def related_to(self, obj, queryset=None):
42 return self.intermediary_table_model.objects.get_related(
45 return self.intermediary_table_model.objects.get_related(
48 def with_all(self, tags, queryset=None):
50 return self.intermediary_table_model.objects.get_by_model(self.model, tags)
52 return self.intermediary_table_model.objects.get_by_model(queryset, tags)
54 def with_any(self, tags, queryset=None):
56 return self.intermediary_table_model.objects.get_union_by_model(self.model, tags)
58 return self.intermediary_table_model.objects.get_union_by_model(queryset, tags)
61 class TagDescriptor(object):
63 A descriptor which provides access to a ``ModelTagManager`` for
64 model classes and simple retrieval, updating and deletion of tags
67 def __init__(self, tag_model):
68 self.tag_model = tag_model
70 def __get__(self, instance, owner):
72 tag_manager = ModelTagManager(self.tag_model)
73 tag_manager.model = owner
76 return self.tag_model.objects.get_for_object(instance)
78 def __set__(self, instance, value):
79 self.tag_model.objects.update_tags(instance, value)
81 def __del__(self, instance):
82 self.tag_model.objects.update_tags(instance, [])