Removed jquery.cuteform.js.
[wolnelektury.git] / newtagging / models.py
1 """
2 Models and managers for generic tagging.
3 """
4 # Python 2.3 compatibility
5 if not hasattr(__builtins__, 'set'):
6     from sets import Set as set
7
8 from django.contrib.contenttypes import generic
9 from django.contrib.contenttypes.models import ContentType
10 from django.db import connection, models
11 from django.db.models.query import QuerySet
12 from django.utils.translation import ugettext_lazy as _
13 from django.db.models.base import ModelBase
14
15 from newtagging.utils import get_tag_list, get_queryset_and_model
16
17 qn = connection.ops.quote_name
18
19 try:
20     from django.db.models.query import parse_lookup
21 except ImportError:
22     parse_lookup = None
23
24
25 ############
26 # Managers #
27 ############
28
29 class TagManager(models.Manager):
30     def __init__(self, intermediary_table_model):
31         super(TagManager, self).__init__()
32         self.intermediary_table_model = intermediary_table_model
33     
34     def update_tags(self, obj, tags):
35         """
36         Update tags associated with an object.
37         """
38         content_type = ContentType.objects.get_for_model(obj)
39         current_tags = list(self.filter(items__content_type__pk=content_type.pk,
40                                         items__object_id=obj.pk))
41         updated_tags = get_tag_list(tags)
42     
43         # Remove tags which no longer apply
44         tags_for_removal = [tag for tag in current_tags \
45                             if tag not in updated_tags]
46         if len(tags_for_removal):
47             self.intermediary_table_model._default_manager.filter(content_type__pk=content_type.pk,
48                                                object_id=obj.pk,
49                                                tag__in=tags_for_removal).delete()
50         # Add new tags
51         for tag in updated_tags:
52             if tag not in current_tags:
53                 self.intermediary_table_model._default_manager.create(tag=tag, content_object=obj)
54     
55     # def add_tag(self, obj, tag_name):
56     #     """
57     #     Associates the given object with a tag.
58     #     """
59     #     tag_names = parse_tag_input(tag_name)
60     #     if not len(tag_names):
61     #         raise AttributeError(_('No tags were given: "%s".') % tag_name)
62     #     if len(tag_names) > 1:
63     #         raise AttributeError(_('Multiple tags were given: "%s".') % tag_name)
64     #     tag_name = tag_names[0]
65     #     # if settings.FORCE_LOWERCASE_TAGS:
66     #     #     tag_name = tag_name.lower()
67     #     tag, created = self.get_or_create(name=tag_name)
68     #     ctype = ContentType.objects.get_for_model(obj)
69     #     self.intermediary_table_model._default_manager.get_or_create(
70     #         tag=tag, content_type=ctype, object_id=obj.pk)
71
72     def get_for_object(self, obj):
73         """
74         Create a queryset matching all tags associated with the given
75         object.
76         """
77         ctype = ContentType.objects.get_for_model(obj)
78         return self.filter(items__content_type__pk=ctype.pk,
79                            items__object_id=obj.pk)
80
81     def _get_usage(self, model, counts=False, min_count=None, extra_joins=None, extra_criteria=None, params=None, extra=None):
82         """
83         Perform the custom SQL query for ``usage_for_model`` and
84         ``usage_for_queryset``.
85         """
86         if min_count is not None: counts = True
87
88         model_table = qn(model._meta.db_table)
89         model_pk = '%s.%s' % (model_table, qn(model._meta.pk.column))
90         tag_columns = self._get_tag_columns()
91         
92         if extra is None: extra = {}
93         extra_where = ''
94         if 'where' in extra:
95             extra_where = 'AND ' + ' AND '.join(extra['where'])
96         
97         query = """
98         SELECT DISTINCT %(tag_columns)s%(count_sql)s
99         FROM
100             %(tag)s
101             INNER JOIN %(tagged_item)s
102                 ON %(tag)s.id = %(tagged_item)s.tag_id
103             INNER JOIN %(model)s
104                 ON %(tagged_item)s.object_id = %(model_pk)s
105             %%s
106         WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
107             %%s
108             %(extra_where)s
109         GROUP BY %(tag)s.id, %(tag)s.name
110         %%s
111         ORDER BY %(tag)s.%(ordering)s ASC""" % {
112             'tag': qn(self.model._meta.db_table),
113             'ordering': ', '.join(qn(field) for field in self.model._meta.ordering),
114             'tag_columns': tag_columns,
115             'count_sql': counts and (', COUNT(%s)' % model_pk) or '',
116             'tagged_item': qn(self.intermediary_table_model._meta.db_table),
117             'model': model_table,
118             'model_pk': model_pk,
119             'extra_where': extra_where,
120             'content_type_id': ContentType.objects.get_for_model(model).pk,
121         }
122
123         min_count_sql = ''
124         if min_count is not None:
125             min_count_sql = 'HAVING COUNT(%s) >= %%s' % model_pk
126             params.append(min_count)
127
128         cursor = connection.cursor()
129         cursor.execute(query % (extra_joins, extra_criteria, min_count_sql), params)
130         tags = []
131         for row in cursor.fetchall():
132             t = self.model(*row[:len(self.model._meta.fields)])
133             if counts:
134                 t.count = row[len(self.model._meta.fields)]
135             tags.append(t)
136         return tags
137
138     def usage_for_model(self, model, counts=False, min_count=None, filters=None, extra=None):
139         """
140         Obtain a list of tags associated with instances of the given
141         Model class.
142
143         If ``counts`` is True, a ``count`` attribute will be added to
144         each tag, indicating how many times it has been used against
145         the Model class in question.
146
147         If ``min_count`` is given, only tags which have a ``count``
148         greater than or equal to ``min_count`` will be returned.
149         Passing a value for ``min_count`` implies ``counts=True``.
150
151         To limit the tags (and counts, if specified) returned to those
152         used by a subset of the Model's instances, pass a dictionary
153         of field lookups to be applied to the given Model as the
154         ``filters`` argument.
155         """
156         if extra is None: extra = {}
157         if filters is None: filters = {}
158
159         if not parse_lookup:
160             # post-queryset-refactor (hand off to usage_for_queryset)
161             queryset = model._default_manager.filter()
162             for f in filters.items():
163                 queryset.query.add_filter(f)
164             usage = self.usage_for_queryset(queryset, counts, min_count, extra)
165         else:
166             # pre-queryset-refactor
167             extra_joins = ''
168             extra_criteria = ''
169             params = []
170             if len(filters) > 0:
171                 joins, where, params = parse_lookup(filters.items(), model._meta)
172                 extra_joins = ' '.join(['%s %s AS %s ON %s' % (join_type, table, alias, condition)
173                                         for (alias, (table, join_type, condition)) in joins.items()])
174                 extra_criteria = 'AND %s' % (' AND '.join(where))
175             usage = self._get_usage(model, counts, min_count, extra_joins, extra_criteria, params, extra)
176
177         return usage
178
179     def usage_for_queryset(self, queryset, counts=False, min_count=None, extra=None):
180         """
181         Obtain a list of tags associated with instances of a model
182         contained in the given queryset.
183
184         If ``counts`` is True, a ``count`` attribute will be added to
185         each tag, indicating how many times it has been used against
186         the Model class in question.
187
188         If ``min_count`` is given, only tags which have a ``count``
189         greater than or equal to ``min_count`` will be returned.
190         Passing a value for ``min_count`` implies ``counts=True``.
191         """
192         if parse_lookup:
193             raise AttributeError("'TagManager.usage_for_queryset' is not compatible with pre-queryset-refactor versions of Django.")
194
195         extra_joins = ' '.join(queryset.query.get_from_clause()[0][1:])
196         where, params = queryset.query.where.as_sql()
197         if where:
198             extra_criteria = 'AND %s' % where
199         else:
200             extra_criteria = ''
201         return self._get_usage(queryset.model, counts, min_count, extra_joins, extra_criteria, params, extra)
202
203     def related_for_model(self, tags, model, counts=False, min_count=None, extra=None):
204         """
205         Obtain a list of tags related to a given list of tags - that
206         is, other tags used by items which have all the given tags.
207
208         If ``counts`` is True, a ``count`` attribute will be added to
209         each tag, indicating the number of items which have it in
210         addition to the given list of tags.
211
212         If ``min_count`` is given, only tags which have a ``count``
213         greater than or equal to ``min_count`` will be returned.
214         Passing a value for ``min_count`` implies ``counts=True``.
215         """
216         if min_count is not None: counts = True
217         tags = get_tag_list(tags)
218         tag_count = len(tags)
219         tagged_item_table = qn(self.intermediary_table_model._meta.db_table)
220         tag_columns = self._get_tag_columns()
221         
222         if extra is None: extra = {}
223         extra_where = ''
224         if 'where' in extra:
225             extra_where = 'AND ' + ' AND '.join(extra['where'])
226         
227         query = """
228         SELECT %(tag_columns)s%(count_sql)s
229         FROM %(tagged_item)s INNER JOIN %(tag)s ON %(tagged_item)s.tag_id = %(tag)s.id
230         WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
231           AND %(tagged_item)s.object_id IN
232           (
233               SELECT %(tagged_item)s.object_id
234               FROM %(tagged_item)s, %(tag)s
235               WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
236                 AND %(tag)s.id = %(tagged_item)s.tag_id
237                 AND %(tag)s.id IN (%(tag_id_placeholders)s)
238               GROUP BY %(tagged_item)s.object_id
239               HAVING COUNT(%(tagged_item)s.object_id) = %(tag_count)s
240           )
241           AND %(tag)s.id NOT IN (%(tag_id_placeholders)s)
242           %(extra_where)s
243         GROUP BY %(tag)s.id, %(tag)s.name
244         %(min_count_sql)s
245         ORDER BY %(tag)s.%(ordering)s ASC""" % {
246             'tag': qn(self.model._meta.db_table),
247             'ordering': ', '.join(qn(field) for field in self.model._meta.ordering),
248             'tag_columns': tag_columns,
249             'count_sql': counts and ', COUNT(%s.object_id)' % tagged_item_table or '',
250             'tagged_item': tagged_item_table,
251             'content_type_id': ContentType.objects.get_for_model(model).pk,
252             'tag_id_placeholders': ','.join(['%s'] * tag_count),
253             'extra_where': extra_where,
254             'tag_count': tag_count,
255             'min_count_sql': min_count is not None and ('HAVING COUNT(%s.object_id) >= %%s' % tagged_item_table) or '',
256         }
257
258         params = [tag.pk for tag in tags] * 2
259         if min_count is not None:
260             params.append(min_count)
261
262         cursor = connection.cursor()
263         cursor.execute(query, params)
264         related = []
265         for row in cursor.fetchall():
266             tag = self.model(*row[:len(self.model._meta.fields)])
267             if counts is True:
268                 tag.count = row[len(self.model._meta.fields)]
269             related.append(tag)
270         return related
271
272     def _get_tag_columns(self):
273         tag_table = qn(self.model._meta.db_table)
274         return ', '.join('%s.%s' % (tag_table, qn(field.column)) for field in self.model._meta.fields)
275
276
277 class TaggedItemManager(models.Manager):
278     """
279     FIXME There's currently no way to get the ``GROUP BY`` and ``HAVING``
280           SQL clauses required by many of this manager's methods into
281           Django's ORM.
282
283           For now, we manually execute a query to retrieve the PKs of
284           objects we're interested in, then use the ORM's ``__in``
285           lookup to return a ``QuerySet``.
286
287           Once the queryset-refactor branch lands in trunk, this can be
288           tidied up significantly.
289     """
290     def get_by_model(self, queryset_or_model, tags):
291         """
292         Create a ``QuerySet`` containing instances of the specified
293         model associated with a given tag or list of tags.
294         """
295         tags = get_tag_list(tags)
296         tag_count = len(tags)
297         if tag_count == 0:
298             # No existing tags were given
299             queryset, model = get_queryset_and_model(queryset_or_model)
300             return model._default_manager.none()
301         elif tag_count == 1:
302             # Optimisation for single tag - fall through to the simpler
303             # query below.
304             tag = tags[0]
305         else:
306             return self.get_intersection_by_model(queryset_or_model, tags)
307
308         queryset, model = get_queryset_and_model(queryset_or_model)
309         content_type = ContentType.objects.get_for_model(model)
310         opts = self.model._meta
311         tagged_item_table = qn(opts.db_table)
312         return queryset.extra(
313             tables=[opts.db_table],
314             where=[
315                 '%s.content_type_id = %%s' % tagged_item_table,
316                 '%s.tag_id = %%s' % tagged_item_table,
317                 '%s.%s = %s.object_id' % (qn(model._meta.db_table),
318                                           qn(model._meta.pk.column),
319                                           tagged_item_table)
320             ],
321             params=[content_type.pk, tag.pk],
322         )
323
324     def get_intersection_by_model(self, queryset_or_model, tags):
325         """
326         Create a ``QuerySet`` containing instances of the specified
327         model associated with *all* of the given list of tags.
328         """
329         tags = get_tag_list(tags)
330         tag_count = len(tags)
331         queryset, model = get_queryset_and_model(queryset_or_model)
332
333         if not tag_count:
334             return model._default_manager.none()
335
336         model_table = qn(model._meta.db_table)
337         # This query selects the ids of all objects which have all the
338         # given tags.
339         query = """
340         SELECT %(model_pk)s
341         FROM %(model)s, %(tagged_item)s
342         WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
343           AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
344           AND %(model_pk)s = %(tagged_item)s.object_id
345         GROUP BY %(model_pk)s
346         HAVING COUNT(%(model_pk)s) = %(tag_count)s""" % {
347             'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
348             'model': model_table,
349             'tagged_item': qn(self.model._meta.db_table),
350             'content_type_id': ContentType.objects.get_for_model(model).pk,
351             'tag_id_placeholders': ','.join(['%s'] * tag_count),
352             'tag_count': tag_count,
353         }
354
355         cursor = connection.cursor()
356         cursor.execute(query, [tag.pk for tag in tags])
357         object_ids = [row[0] for row in cursor.fetchall()]
358         if len(object_ids) > 0:
359             return queryset.filter(pk__in=object_ids)
360         else:
361             return model._default_manager.none()
362
363     def get_union_by_model(self, queryset_or_model, tags):
364         """
365         Create a ``QuerySet`` containing instances of the specified
366         model associated with *any* of the given list of tags.
367         """
368         tags = get_tag_list(tags)
369         tag_count = len(tags)
370         queryset, model = get_queryset_and_model(queryset_or_model)
371
372         if not tag_count:
373             return model._default_manager.none()
374
375         model_table = qn(model._meta.db_table)
376         # This query selects the ids of all objects which have any of
377         # the given tags.
378         query = """
379         SELECT %(model_pk)s
380         FROM %(model)s, %(tagged_item)s
381         WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
382           AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
383           AND %(model_pk)s = %(tagged_item)s.object_id
384         GROUP BY %(model_pk)s""" % {
385             'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
386             'model': model_table,
387             'tagged_item': qn(self.model._meta.db_table),
388             'content_type_id': ContentType.objects.get_for_model(model).pk,
389             'tag_id_placeholders': ','.join(['%s'] * tag_count),
390         }
391
392         cursor = connection.cursor()
393         cursor.execute(query, [tag.pk for tag in tags])
394         object_ids = [row[0] for row in cursor.fetchall()]
395         if len(object_ids) > 0:
396             return queryset.filter(pk__in=object_ids)
397         else:
398             return model._default_manager.none()
399
400     def get_related(self, obj, queryset_or_model, num=None):
401         """
402         Retrieve a list of instances of the specified model which share
403         tags with the model instance ``obj``, ordered by the number of
404         shared tags in descending order.
405
406         If ``num`` is given, a maximum of ``num`` instances will be
407         returned.
408         """
409         queryset, model = get_queryset_and_model(queryset_or_model)
410         model_table = qn(model._meta.db_table)
411         content_type = ContentType.objects.get_for_model(obj)
412         related_content_type = ContentType.objects.get_for_model(model)
413         query = """
414         SELECT %(model_pk)s, COUNT(related_tagged_item.object_id) AS %(count)s
415         FROM %(model)s, %(tagged_item)s, %(tag)s, %(tagged_item)s related_tagged_item
416         WHERE %(tagged_item)s.object_id = %%s
417           AND %(tagged_item)s.content_type_id = %(content_type_id)s
418           AND %(tag)s.id = %(tagged_item)s.tag_id
419           AND related_tagged_item.content_type_id = %(related_content_type_id)s
420           AND related_tagged_item.tag_id = %(tagged_item)s.tag_id
421           AND %(model_pk)s = related_tagged_item.object_id"""
422         if content_type.pk == related_content_type.pk:
423             # Exclude the given instance itself if determining related
424             # instances for the same model.
425             query += """
426           AND related_tagged_item.object_id != %(tagged_item)s.object_id"""
427         query += """
428         GROUP BY %(model_pk)s
429         ORDER BY %(count)s DESC
430         %(limit_offset)s"""
431         query = query % {
432             'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
433             'count': qn('count'),
434             'model': model_table,
435             'tagged_item': qn(self.model._meta.db_table),
436             'tag': qn(self.model._meta.get_field('tag').rel.to._meta.db_table),
437             'content_type_id': content_type.pk,
438             'related_content_type_id': related_content_type.pk,
439             'limit_offset': num is not None and connection.ops.limit_offset_sql(num) or '',
440         }
441
442         cursor = connection.cursor()
443         cursor.execute(query, [obj.pk])
444         object_ids = [row[0] for row in cursor.fetchall()]
445         if len(object_ids) > 0:
446             # Use in_bulk here instead of an id__in lookup, because id__in would
447             # clobber the ordering.
448             object_dict = queryset.in_bulk(object_ids)
449             return [object_dict[object_id] for object_id in object_ids \
450                     if object_id in object_dict]
451         else:
452             return []
453
454
455 ##########
456 # Models #
457 ##########
458 def create_intermediary_table_model(model):
459     """Create an intermediary table model for the specific tag model"""
460     name = model.__name__ + 'Relation'
461      
462     class Meta:
463         db_table = '%s_relation' % model._meta.db_table
464         unique_together = (('tag', 'content_type', 'object_id'),)
465
466     def obj_unicode(self):
467         return u'%s [%s]' % (self.content_type.get_object_for_this_type(pk=self.object_id), self.tag)
468         
469     # Set up a dictionary to simulate declarations within a class    
470     attrs = {
471         '__module__': model.__module__,
472         'Meta': Meta,
473         'tag': models.ForeignKey(model, verbose_name=_('tag'), related_name='items'),
474         'content_type': models.ForeignKey(ContentType, verbose_name=_('content type')),
475         'object_id': models.PositiveIntegerField(_('object id'), db_index=True),
476         'content_object': generic.GenericForeignKey('content_type', 'object_id'),
477         '__unicode__': obj_unicode,
478     }
479
480     return type(name, (models.Model,), attrs)
481
482
483 class TagMeta(ModelBase):
484     "Metaclass for tag models (models inheriting from TagBase)."
485     def __new__(cls, name, bases, attrs):
486         model = super(TagMeta, cls).__new__(cls, name, bases, attrs)
487         if not model._meta.abstract:
488             # Create an intermediary table and register custom managers for concrete models
489             intermediary_table_model = create_intermediary_table_model(model)
490             TagManager(intermediary_table_model).contribute_to_class(model, 'objects')
491             TaggedItemManager().contribute_to_class(intermediary_table_model, 'objects')
492         return model
493
494
495 class TagBase(models.Model):
496     """Abstract class to be inherited by model classes."""
497     __metaclass__ = TagMeta
498     
499     class Meta:
500         abstract = True
501