]> git.openstreetmap.org Git - osqa.git/blob - forum/models/tag.py
791636fa0a9810f2dee4c935d8bc5304d64d9bf0
[osqa.git] / forum / models / tag.py
1 import datetime
2 from base import *
3
4 from django.conf import settings as django_settings
5 from django.core.cache.backends.base import BaseCache
6 from django.utils.translation import ugettext as _
7 from django.utils.encoding import smart_unicode, force_unicode
8
9 from forum import modules
10
11 class ActiveTagManager(CachedManager):
12     use_for_related_fields = True
13
14     def get_query_set(self):
15         return super(ActiveTagManager, self).get_query_set().exclude(used_count__lt=1)
16
17 class Tag(BaseModel):
18     name            = models.CharField(max_length=255, unique=True)
19     created_by      = models.ForeignKey(User, related_name='created_tags')
20     created_at      = models.DateTimeField(default=datetime.datetime.now, blank=True, null=True)
21     marked_by       = models.ManyToManyField(User, related_name="marked_tags", through="MarkedTag")
22     # Denormalised data
23     used_count = models.PositiveIntegerField(default=0)
24
25     active = ActiveTagManager()
26
27     class Meta:
28         ordering = ('-used_count', 'name')
29         app_label = 'forum'
30
31     def __unicode__(self):
32         return force_unicode(self.name)
33
34     def add_to_usage_count(self, value):
35         if int(self.used_count + value) < 0:
36             self.used_count = 0
37         else:
38             self.used_count += value
39
40         self.save()
41
42     def cache_key(self):
43         return self._generate_cache_key(Tag.safe_cache_name(self.name))
44
45     @classmethod
46     def safe_cache_name(cls, name):
47         return "".join([str(ord(c)) for c in name])
48
49     @classmethod
50     def infer_cache_key(cls, querydict):
51         if 'name' in querydict:
52             cache_key = cls._generate_cache_key(cls.safe_cache_name(querydict['name']))
53
54             if len(cache_key) > django_settings.CACHE_MAX_KEY_LENGTH:
55                 cache_key = cache_key[:django_settings.CACHE_MAX_KEY_LENGTH]
56
57             return cache_key
58
59         return None
60
61     @classmethod
62     def value_to_list_on_cache_query(cls):
63         return 'name'
64
65     @models.permalink
66     def get_absolute_url(self):
67         return ('tag_questions', (), {'tag': self.name})
68
69 class MarkedTag(models.Model):
70     TAG_MARK_REASONS = (('good', _('interesting')), ('bad', _('ignored')))
71     tag = models.ForeignKey(Tag, related_name='user_selections')
72     user = models.ForeignKey(User, related_name='tag_selections')
73     reason = models.CharField(max_length=16, choices=TAG_MARK_REASONS)
74
75     class Meta:
76         app_label = 'forum'
77