2 Models and managers for generic tagging.
 
   4 # Python 2.3 compatibility
 
   5 if not hasattr(__builtins__, 'set'):
 
   6     from sets import Set as set
 
   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
 
  14 qn = connection.ops.quote_name
 
  17     from django.db.models.query import parse_lookup
 
  22 def get_queryset_and_model(queryset_or_model):
 
  24     Given a ``QuerySet`` or a ``Model``, returns a two-tuple of
 
  27     If a ``Model`` is given, the ``QuerySet`` returned will be created
 
  28     using its default manager.
 
  31         return queryset_or_model, queryset_or_model.model
 
  32     except AttributeError:
 
  33         return queryset_or_model._default_manager.all(), queryset_or_model
 
  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
 
  44     def update_tags(self, obj, tags):
 
  46         Update tags associated with an object.
 
  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)
 
  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,
 
  59                                                tag__in=tags_for_removal).delete()
 
  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)
 
  65     def remove_tag(self, obj, tag):
 
  67         Remove tag from an object.
 
  69         content_type = ContentType.objects.get_for_model(obj)
 
  70         self.intermediary_table_model._default_manager.filter(content_type__pk=content_type.pk,
 
  71             object_id=obj.pk, tag=tag).delete()
 
  73     def get_for_object(self, obj):
 
  75         Create a queryset matching all tags associated with the given
 
  78         ctype = ContentType.objects.get_for_model(obj)
 
  79         return self.filter(items__content_type__pk=ctype.pk,
 
  80                            items__object_id=obj.pk)
 
  82     def _get_usage(self, model, counts=False, min_count=None, extra_joins=None, extra_criteria=None, params=None, extra=None):
 
  84         Perform the custom SQL query for ``usage_for_model`` and
 
  85         ``usage_for_queryset``.
 
  87         if min_count is not None: counts = True
 
  89         model_table = qn(model._meta.db_table)
 
  90         model_pk = '%s.%s' % (model_table, qn(model._meta.pk.column))
 
  91         tag_columns = self._get_tag_columns()
 
  93         if extra is None: extra = {}
 
  96             extra_where = 'AND ' + ' AND '.join(extra['where'])
 
  99         SELECT DISTINCT %(tag_columns)s%(count_sql)s
 
 102             INNER JOIN %(tagged_item)s
 
 103                 ON %(tag)s.id = %(tagged_item)s.tag_id
 
 105                 ON %(tagged_item)s.object_id = %(model_pk)s
 
 107         WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
 
 110         GROUP BY %(tag)s.id, %(tag)s.name
 
 112         ORDER BY %(tag)s.%(ordering)s ASC""" % {
 
 113             'tag': qn(self.model._meta.db_table),
 
 114             'ordering': ', '.join(qn(field) for field in self.model._meta.ordering),
 
 115             'tag_columns': tag_columns,
 
 116             'count_sql': counts and (', COUNT(%s)' % model_pk) or '',
 
 117             'tagged_item': qn(self.intermediary_table_model._meta.db_table),
 
 118             'model': model_table,
 
 119             'model_pk': model_pk,
 
 120             'extra_where': extra_where,
 
 121             'content_type_id': ContentType.objects.get_for_model(model).pk,
 
 125         if min_count is not None:
 
 126             min_count_sql = 'HAVING COUNT(%s) >= %%s' % model_pk
 
 127             params.append(min_count)
 
 129         cursor = connection.cursor()
 
 130         cursor.execute(query % (extra_joins, extra_criteria, min_count_sql), params)
 
 132         for row in cursor.fetchall():
 
 133             t = self.model(*row[:len(self.model._meta.fields)])
 
 135                 t.count = row[len(self.model._meta.fields)]
 
 139     def usage_for_model(self, model, counts=False, min_count=None, filters=None, extra=None):
 
 141         Obtain a list of tags associated with instances of the given
 
 144         If ``counts`` is True, a ``count`` attribute will be added to
 
 145         each tag, indicating how many times it has been used against
 
 146         the Model class in question.
 
 148         If ``min_count`` is given, only tags which have a ``count``
 
 149         greater than or equal to ``min_count`` will be returned.
 
 150         Passing a value for ``min_count`` implies ``counts=True``.
 
 152         To limit the tags (and counts, if specified) returned to those
 
 153         used by a subset of the Model's instances, pass a dictionary
 
 154         of field lookups to be applied to the given Model as the
 
 155         ``filters`` argument.
 
 157         if extra is None: extra = {}
 
 158         if filters is None: filters = {}
 
 161             # post-queryset-refactor (hand off to usage_for_queryset)
 
 162             queryset = model._default_manager.filter()
 
 163             for f in filters.items():
 
 164                 queryset.query.add_filter(f)
 
 165             usage = self.usage_for_queryset(queryset, counts, min_count, extra)
 
 167             # pre-queryset-refactor
 
 172                 joins, where, params = parse_lookup(filters.items(), model._meta)
 
 173                 extra_joins = ' '.join(['%s %s AS %s ON %s' % (join_type, table, alias, condition)
 
 174                                         for (alias, (table, join_type, condition)) in joins.items()])
 
 175                 extra_criteria = 'AND %s' % (' AND '.join(where))
 
 176             usage = self._get_usage(model, counts, min_count, extra_joins, extra_criteria, params, extra)
 
 180     def usage_for_queryset(self, queryset, counts=False, min_count=None, extra=None):
 
 182         Obtain a list of tags associated with instances of a model
 
 183         contained in the given queryset.
 
 185         If ``counts`` is True, a ``count`` attribute will be added to
 
 186         each tag, indicating how many times it has been used against
 
 187         the Model class in question.
 
 189         If ``min_count`` is given, only tags which have a ``count``
 
 190         greater than or equal to ``min_count`` will be returned.
 
 191         Passing a value for ``min_count`` implies ``counts=True``.
 
 194             raise AttributeError("'TagManager.usage_for_queryset' is not compatible with pre-queryset-refactor versions of Django.")
 
 196         extra_joins = ' '.join(queryset.query.get_from_clause()[0][1:])
 
 197         where, params = queryset.query.where.as_sql()
 
 199             extra_criteria = 'AND %s' % where
 
 202         return self._get_usage(queryset.model, counts, min_count, extra_joins, extra_criteria, params, extra)
 
 204     def related_for_model(self, tags, model, counts=False, min_count=None, extra=None):
 
 206         Obtain a list of tags related to a given list of tags - that
 
 207         is, other tags used by items which have all the given tags.
 
 209         If ``counts`` is True, a ``count`` attribute will be added to
 
 210         each tag, indicating the number of items which have it in
 
 211         addition to the given list of tags.
 
 213         If ``min_count`` is given, only tags which have a ``count``
 
 214         greater than or equal to ``min_count`` will be returned.
 
 215         Passing a value for ``min_count`` implies ``counts=True``.
 
 217         if min_count is not None: counts = True
 
 218         tags = self.model.get_tag_list(tags)
 
 219         tag_count = len(tags)
 
 220         tagged_item_table = qn(self.intermediary_table_model._meta.db_table)
 
 221         tag_columns = self._get_tag_columns()
 
 223         if extra is None: extra = {}
 
 226             extra_where = 'AND ' + ' AND '.join(extra['where'])
 
 228         # Temporary table in this query is a hack to prevent MySQL from executing
 
 229         # inner query as dependant query (which could result in severe performance loss)
 
 231         SELECT %(tag_columns)s%(count_sql)s
 
 232         FROM %(tagged_item)s INNER JOIN %(tag)s ON %(tagged_item)s.tag_id = %(tag)s.id
 
 233         WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
 
 234         AND %(tagged_item)s.object_id IN
 
 238                 SELECT %(tagged_item)s.object_id
 
 239                 FROM %(tagged_item)s, %(tag)s
 
 240                 WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
 
 241                   AND %(tag)s.id = %(tagged_item)s.tag_id
 
 242                   AND %(tag)s.id IN (%(tag_id_placeholders)s)
 
 243                 GROUP BY %(tagged_item)s.object_id
 
 244                 HAVING COUNT(%(tagged_item)s.object_id) = %(tag_count)s
 
 247         AND %(tag)s.id NOT IN (%(tag_id_placeholders)s)
 
 249         GROUP BY %(tag_columns)s
 
 251         ORDER BY %(tag)s.%(ordering)s ASC""" % {
 
 252             'tag': qn(self.model._meta.db_table),
 
 253             'ordering': ', '.join(qn(field) for field in self.model._meta.ordering),
 
 254             'tag_columns': tag_columns,
 
 255             'count_sql': counts and ', COUNT(%s.object_id)' % tagged_item_table or '',
 
 256             'tagged_item': tagged_item_table,
 
 257             'content_type_id': ContentType.objects.get_for_model(model).pk,
 
 258             'tag_id_placeholders': ','.join(['%s'] * tag_count),
 
 259             'extra_where': extra_where,
 
 260             'tag_count': tag_count,
 
 261             'min_count_sql': min_count is not None and ('HAVING COUNT(%s.object_id) >= %%s' % tagged_item_table) or '',
 
 264         params = [tag.pk for tag in tags] * 2
 
 265         if min_count is not None:
 
 266             params.append(min_count)
 
 268         cursor = connection.cursor()
 
 269         cursor.execute(query, params)
 
 271         for row in cursor.fetchall():
 
 272             tag = self.model(*row[:len(self.model._meta.fields)])
 
 274                 tag.count = row[len(self.model._meta.fields)]
 
 278     def _get_tag_columns(self):
 
 279         tag_table = qn(self.model._meta.db_table)
 
 280         return ', '.join('%s.%s' % (tag_table, qn(field.column)) for field in self.model._meta.fields)
 
 283 class TaggedItemManager(models.Manager):
 
 285     FIXME There's currently no way to get the ``GROUP BY`` and ``HAVING``
 
 286           SQL clauses required by many of this manager's methods into
 
 289           For now, we manually execute a query to retrieve the PKs of
 
 290           objects we're interested in, then use the ORM's ``__in``
 
 291           lookup to return a ``QuerySet``.
 
 293           Once the queryset-refactor branch lands in trunk, this can be
 
 294           tidied up significantly.
 
 296     def __init__(self, tag_model):
 
 297         super(TaggedItemManager, self).__init__()
 
 298         self.tag_model = tag_model
 
 300     def get_by_model(self, queryset_or_model, tags):
 
 302         Create a ``QuerySet`` containing instances of the specified
 
 303         model associated with a given tag or list of tags.
 
 305         tags = self.tag_model.get_tag_list(tags)
 
 306         tag_count = len(tags)
 
 308             # No existing tags were given
 
 309             queryset, model = get_queryset_and_model(queryset_or_model)
 
 310             return model._default_manager.none()
 
 312             # Optimisation for single tag - fall through to the simpler
 
 316             return self.get_intersection_by_model(queryset_or_model, tags)
 
 318         queryset, model = get_queryset_and_model(queryset_or_model)
 
 319         content_type = ContentType.objects.get_for_model(model)
 
 320         opts = self.model._meta
 
 321         tagged_item_table = qn(opts.db_table)
 
 322         return queryset.extra(
 
 323             tables=[opts.db_table],
 
 325                 '%s.content_type_id = %%s' % tagged_item_table,
 
 326                 '%s.tag_id = %%s' % tagged_item_table,
 
 327                 '%s.%s = %s.object_id' % (qn(model._meta.db_table),
 
 328                                           qn(model._meta.pk.column),
 
 331             params=[content_type.pk, tag.pk],
 
 334     def get_intersection_by_model(self, queryset_or_model, tags):
 
 336         Create a ``QuerySet`` containing instances of the specified
 
 337         model associated with *all* of the given list of tags.
 
 339         tags = self.tag_model.get_tag_list(tags)
 
 340         tag_count = len(tags)
 
 341         queryset, model = get_queryset_and_model(queryset_or_model)
 
 344             return model._default_manager.none()
 
 346         model_table = qn(model._meta.db_table)
 
 347         # This query selects the ids of all objects which have all the
 
 351         FROM %(model)s, %(tagged_item)s
 
 352         WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
 
 353           AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
 
 354           AND %(model_pk)s = %(tagged_item)s.object_id
 
 355         GROUP BY %(model_pk)s
 
 356         HAVING COUNT(%(model_pk)s) = %(tag_count)s""" % {
 
 357             'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
 
 358             'model': model_table,
 
 359             'tagged_item': qn(self.model._meta.db_table),
 
 360             'content_type_id': ContentType.objects.get_for_model(model).pk,
 
 361             'tag_id_placeholders': ','.join(['%s'] * tag_count),
 
 362             'tag_count': tag_count,
 
 365         cursor = connection.cursor()
 
 366         cursor.execute(query, [tag.pk for tag in tags])
 
 367         object_ids = [row[0] for row in cursor.fetchall()]
 
 368         if len(object_ids) > 0:
 
 369             return queryset.filter(pk__in=object_ids)
 
 371             return model._default_manager.none()
 
 373     def get_union_by_model(self, queryset_or_model, tags):
 
 375         Create a ``QuerySet`` containing instances of the specified
 
 376         model associated with *any* of the given list of tags.
 
 378         tags = self.tag_model.get_tag_list(tags)
 
 379         tag_count = len(tags)
 
 380         queryset, model = get_queryset_and_model(queryset_or_model)
 
 383             return model._default_manager.none()
 
 385         model_table = qn(model._meta.db_table)
 
 386         # This query selects the ids of all objects which have any of
 
 390         FROM %(model)s, %(tagged_item)s
 
 391         WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
 
 392           AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
 
 393           AND %(model_pk)s = %(tagged_item)s.object_id
 
 394         GROUP BY %(model_pk)s""" % {
 
 395             'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
 
 396             'model': model_table,
 
 397             'tagged_item': qn(self.model._meta.db_table),
 
 398             'content_type_id': ContentType.objects.get_for_model(model).pk,
 
 399             'tag_id_placeholders': ','.join(['%s'] * tag_count),
 
 402         cursor = connection.cursor()
 
 403         cursor.execute(query, [tag.pk for tag in tags])
 
 404         object_ids = [row[0] for row in cursor.fetchall()]
 
 405         if len(object_ids) > 0:
 
 406             return queryset.filter(pk__in=object_ids)
 
 408             return model._default_manager.none()
 
 410     def get_related(self, obj, queryset_or_model, num=None):
 
 412         Retrieve a list of instances of the specified model which share
 
 413         tags with the model instance ``obj``, ordered by the number of
 
 414         shared tags in descending order.
 
 416         If ``num`` is given, a maximum of ``num`` instances will be
 
 419         queryset, model = get_queryset_and_model(queryset_or_model)
 
 420         model_table = qn(model._meta.db_table)
 
 421         content_type = ContentType.objects.get_for_model(obj)
 
 422         related_content_type = ContentType.objects.get_for_model(model)
 
 424         SELECT %(model_pk)s, COUNT(related_tagged_item.object_id) AS %(count)s
 
 425         FROM %(model)s, %(tagged_item)s, %(tag)s, %(tagged_item)s related_tagged_item
 
 426         WHERE %(tagged_item)s.object_id = %%s
 
 427           AND %(tagged_item)s.content_type_id = %(content_type_id)s
 
 428           AND %(tag)s.id = %(tagged_item)s.tag_id
 
 429           AND related_tagged_item.content_type_id = %(related_content_type_id)s
 
 430           AND related_tagged_item.tag_id = %(tagged_item)s.tag_id
 
 431           AND %(model_pk)s = related_tagged_item.object_id"""
 
 432         if content_type.pk == related_content_type.pk:
 
 433             # Exclude the given instance itself if determining related
 
 434             # instances for the same model.
 
 436           AND related_tagged_item.object_id != %(tagged_item)s.object_id"""
 
 438         GROUP BY %(model_pk)s
 
 439         ORDER BY %(count)s DESC
 
 442             'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
 
 443             'count': qn('count'),
 
 444             'model': model_table,
 
 445             'tagged_item': qn(self.model._meta.db_table),
 
 446             'tag': qn(self.model._meta.get_field('tag').rel.to._meta.db_table),
 
 447             'content_type_id': content_type.pk,
 
 448             'related_content_type_id': related_content_type.pk,
 
 449             'limit_offset': num is not None and connection.ops.limit_offset_sql(num) or '',
 
 452         cursor = connection.cursor()
 
 453         cursor.execute(query, [obj.pk])
 
 454         object_ids = [row[0] for row in cursor.fetchall()]
 
 455         if len(object_ids) > 0:
 
 456             # Use in_bulk here instead of an id__in lookup, because id__in would
 
 457             # clobber the ordering.
 
 458             object_dict = queryset.in_bulk(object_ids)
 
 459             return [object_dict[object_id] for object_id in object_ids \
 
 460                     if object_id in object_dict]
 
 468 def create_intermediary_table_model(model):
 
 469     """Create an intermediary table model for the specific tag model"""
 
 470     name = model.__name__ + 'Relation'
 
 473         db_table = '%s_relation' % model._meta.db_table
 
 474         unique_together = (('tag', 'content_type', 'object_id'),)
 
 476     def obj_unicode(self):
 
 477         return u'%s [%s]' % (self.content_type.get_object_for_this_type(pk=self.object_id), self.tag)
 
 479     # Set up a dictionary to simulate declarations within a class    
 
 481         '__module__': model.__module__,
 
 483         'tag': models.ForeignKey(model, verbose_name=_('tag'), related_name='items'),
 
 484         'content_type': models.ForeignKey(ContentType, verbose_name=_('content type')),
 
 485         'object_id': models.PositiveIntegerField(_('object id'), db_index=True),
 
 486         'content_object': generic.GenericForeignKey('content_type', 'object_id'),
 
 487         '__unicode__': obj_unicode,
 
 490     return type(name, (models.Model,), attrs)
 
 493 class TagMeta(ModelBase):
 
 494     "Metaclass for tag models (models inheriting from TagBase)."
 
 495     def __new__(cls, name, bases, attrs):
 
 496         model = super(TagMeta, cls).__new__(cls, name, bases, attrs)
 
 497         if not model._meta.abstract:
 
 498             # Create an intermediary table and register custom managers for concrete models
 
 499             model.intermediary_table_model = create_intermediary_table_model(model)
 
 500             TagManager(model.intermediary_table_model).contribute_to_class(model, 'objects')
 
 501             TaggedItemManager(model).contribute_to_class(model.intermediary_table_model, 'objects')
 
 505 class TagBase(models.Model):
 
 506     """Abstract class to be inherited by model classes."""
 
 507     __metaclass__ = TagMeta
 
 513     def get_tag_list(tag_list):
 
 515         Utility function for accepting tag input in a flexible manner.
 
 517         You should probably override this method in your subclass.
 
 519         if isinstance(tag_list, TagBase):