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