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
13 from django.core.exceptions import ObjectDoesNotExist
15 qn = connection.ops.quote_name
18 from django.db.models.query import parse_lookup
23 def get_queryset_and_model(queryset_or_model):
25 Given a ``QuerySet`` or a ``Model``, returns a two-tuple of
28 If a ``Model`` is given, the ``QuerySet`` returned will be created
29 using its default manager.
32 return queryset_or_model, queryset_or_model.model
33 except AttributeError:
34 return queryset_or_model._default_manager.all(), queryset_or_model
40 class TagManager(models.Manager):
41 def __init__(self, intermediary_table_model):
42 super(TagManager, self).__init__()
43 self.intermediary_table_model = intermediary_table_model
45 def update_tags(self, obj, tags):
47 Update tags associated with an object.
49 content_type = ContentType.objects.get_for_model(obj)
50 current_tags = list(self.filter(items__content_type__pk=content_type.pk,
51 items__object_id=obj.pk))
52 updated_tags = self.model.get_tag_list(tags)
54 # Remove tags which no longer apply
55 tags_for_removal = [tag for tag in current_tags \
56 if tag not in updated_tags]
57 if len(tags_for_removal):
58 self.intermediary_table_model._default_manager.filter(content_type__pk=content_type.pk,
60 tag__in=tags_for_removal).delete()
62 for tag in updated_tags:
63 if tag not in current_tags:
64 self.intermediary_table_model._default_manager.create(tag=tag, content_object=obj)
66 def remove_tag(self, obj, tag):
68 Remove tag from an object.
70 content_type = ContentType.objects.get_for_model(obj)
71 self.intermediary_table_model._default_manager.filter(content_type__pk=content_type.pk,
72 object_id=obj.pk, tag=tag).delete()
74 def get_for_object(self, obj):
76 Create a queryset matching all tags associated with the given
79 ctype = ContentType.objects.get_for_model(obj)
80 return self.filter(items__content_type__pk=ctype.pk,
81 items__object_id=obj.pk)
83 def _get_usage(self, model, counts=False, min_count=None, extra_joins=None, extra_criteria=None, params=None, extra=None):
85 Perform the custom SQL query for ``usage_for_model`` and
86 ``usage_for_queryset``.
88 if min_count is not None: counts = True
90 model_table = qn(model._meta.db_table)
91 model_pk = '%s.%s' % (model_table, qn(model._meta.pk.column))
92 tag_columns = self._get_tag_columns()
94 if extra is None: extra = {}
97 extra_where = 'AND ' + ' AND '.join(extra['where'])
100 SELECT DISTINCT %(tag_columns)s%(count_sql)s
103 INNER JOIN %(tagged_item)s
104 ON %(tag)s.id = %(tagged_item)s.tag_id
106 ON %(tagged_item)s.object_id = %(model_pk)s
108 WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
111 GROUP BY %(tag)s.id, %(tag)s.name
113 ORDER BY %(tag)s.%(ordering)s ASC""" % {
114 'tag': qn(self.model._meta.db_table),
115 'ordering': ', '.join(qn(field) for field in self.model._meta.ordering),
116 'tag_columns': tag_columns,
117 'count_sql': counts and (', COUNT(%s)' % model_pk) or '',
118 'tagged_item': qn(self.intermediary_table_model._meta.db_table),
119 'model': model_table,
120 'model_pk': model_pk,
121 'extra_where': extra_where,
122 'content_type_id': ContentType.objects.get_for_model(model).pk,
126 if min_count is not None:
127 min_count_sql = 'HAVING COUNT(%s) >= %%s' % model_pk
128 params.append(min_count)
130 cursor = connection.cursor()
131 cursor.execute(query % (extra_joins, extra_criteria, min_count_sql), params)
133 for row in cursor.fetchall():
134 t = self.model(*row[:len(self.model._meta.fields)])
136 t.count = row[len(self.model._meta.fields)]
140 def usage_for_model(self, model, counts=False, min_count=None, filters=None, extra=None):
142 Obtain a list of tags associated with instances of the given
145 If ``counts`` is True, a ``count`` attribute will be added to
146 each tag, indicating how many times it has been used against
147 the Model class in question.
149 If ``min_count`` is given, only tags which have a ``count``
150 greater than or equal to ``min_count`` will be returned.
151 Passing a value for ``min_count`` implies ``counts=True``.
153 To limit the tags (and counts, if specified) returned to those
154 used by a subset of the Model's instances, pass a dictionary
155 of field lookups to be applied to the given Model as the
156 ``filters`` argument.
158 if extra is None: extra = {}
159 if filters is None: filters = {}
162 # post-queryset-refactor (hand off to usage_for_queryset)
163 queryset = model._default_manager.filter()
164 for f in filters.items():
165 queryset.query.add_filter(f)
166 usage = self.usage_for_queryset(queryset, counts, min_count, extra)
168 # pre-queryset-refactor
173 joins, where, params = parse_lookup(filters.items(), model._meta)
174 extra_joins = ' '.join(['%s %s AS %s ON %s' % (join_type, table, alias, condition)
175 for (alias, (table, join_type, condition)) in joins.items()])
176 extra_criteria = 'AND %s' % (' AND '.join(where))
177 usage = self._get_usage(model, counts, min_count, extra_joins, extra_criteria, params, extra)
181 def usage_for_queryset(self, queryset, counts=False, min_count=None, extra=None):
183 Obtain a list of tags associated with instances of a model
184 contained in the given queryset.
186 If ``counts`` is True, a ``count`` attribute will be added to
187 each tag, indicating how many times it has been used against
188 the Model class in question.
190 If ``min_count`` is given, only tags which have a ``count``
191 greater than or equal to ``min_count`` will be returned.
192 Passing a value for ``min_count`` implies ``counts=True``.
195 raise AttributeError("'TagManager.usage_for_queryset' is not compatible with pre-queryset-refactor versions of Django.")
197 extra_joins = ' '.join(queryset.query.get_from_clause()[0][1:])
198 where, params = queryset.query.where.as_sql()
200 extra_criteria = 'AND %s' % where
203 return self._get_usage(queryset.model, counts, min_count, extra_joins, extra_criteria, params, extra)
205 def related_for_model(self, tags, model, counts=False, min_count=None, extra=None):
207 Obtain a list of tags related to a given list of tags - that
208 is, other tags used by items which have all the given tags.
210 If ``counts`` is True, a ``count`` attribute will be added to
211 each tag, indicating the number of items which have it in
212 addition to the given list of tags.
214 If ``min_count`` is given, only tags which have a ``count``
215 greater than or equal to ``min_count`` will be returned.
216 Passing a value for ``min_count`` implies ``counts=True``.
218 if min_count is not None: counts = True
219 tags = self.model.get_tag_list(tags)
220 tag_count = len(tags)
221 tagged_item_table = qn(self.intermediary_table_model._meta.db_table)
222 tag_columns = self._get_tag_columns()
224 if extra is None: extra = {}
227 extra_where = 'AND ' + ' AND '.join(extra['where'])
229 # Temporary table in this query is a hack to prevent MySQL from executing
230 # inner query as dependant query (which could result in severe performance loss)
232 SELECT %(tag_columns)s%(count_sql)s
233 FROM %(tagged_item)s INNER JOIN %(tag)s ON %(tagged_item)s.tag_id = %(tag)s.id
234 WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
235 AND %(tagged_item)s.object_id IN
239 SELECT %(tagged_item)s.object_id
240 FROM %(tagged_item)s, %(tag)s
241 WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
242 AND %(tag)s.id = %(tagged_item)s.tag_id
243 AND %(tag)s.id IN (%(tag_id_placeholders)s)
244 GROUP BY %(tagged_item)s.object_id
245 HAVING COUNT(%(tagged_item)s.object_id) = %(tag_count)s
248 AND %(tag)s.id NOT IN (%(tag_id_placeholders)s)
250 GROUP BY %(tag_columns)s
252 ORDER BY %(tag)s.%(ordering)s ASC""" % {
253 'tag': qn(self.model._meta.db_table),
254 'ordering': ', '.join(qn(field) for field in self.model._meta.ordering),
255 'tag_columns': tag_columns,
256 'count_sql': counts and ', COUNT(%s.object_id)' % tagged_item_table or '',
257 'tagged_item': tagged_item_table,
258 'content_type_id': ContentType.objects.get_for_model(model).pk,
259 'tag_id_placeholders': ','.join(['%s'] * tag_count),
260 'extra_where': extra_where,
261 'tag_count': tag_count,
262 'min_count_sql': min_count is not None and ('HAVING COUNT(%s.object_id) >= %%s' % tagged_item_table) or '',
265 params = [tag.pk for tag in tags] * 2
266 if min_count is not None:
267 params.append(min_count)
269 cursor = connection.cursor()
270 cursor.execute(query, params)
272 for row in cursor.fetchall():
273 tag = self.model(*row[:len(self.model._meta.fields)])
275 tag.count = row[len(self.model._meta.fields)]
279 def _get_tag_columns(self):
280 tag_table = qn(self.model._meta.db_table)
281 return ', '.join('%s.%s' % (tag_table, qn(field.column)) for field in self.model._meta.fields)
284 class TaggedItemManager(models.Manager):
286 FIXME There's currently no way to get the ``GROUP BY`` and ``HAVING``
287 SQL clauses required by many of this manager's methods into
290 For now, we manually execute a query to retrieve the PKs of
291 objects we're interested in, then use the ORM's ``__in``
292 lookup to return a ``QuerySet``.
294 Once the queryset-refactor branch lands in trunk, this can be
295 tidied up significantly.
297 def __init__(self, tag_model):
298 super(TaggedItemManager, self).__init__()
299 self.tag_model = tag_model
301 def get_by_model(self, queryset_or_model, tags):
303 Create a ``QuerySet`` containing instances of the specified
304 model associated with a given tag or list of tags.
306 tags = self.tag_model.get_tag_list(tags)
307 tag_count = len(tags)
309 # No existing tags were given
310 queryset, model = get_queryset_and_model(queryset_or_model)
311 return model._default_manager.none()
313 # Optimisation for single tag - fall through to the simpler
317 return self.get_intersection_by_model(queryset_or_model, tags)
319 queryset, model = get_queryset_and_model(queryset_or_model)
320 content_type = ContentType.objects.get_for_model(model)
321 opts = self.model._meta
322 tagged_item_table = qn(opts.db_table)
323 return queryset.extra(
324 tables=[opts.db_table],
326 '%s.content_type_id = %%s' % tagged_item_table,
327 '%s.tag_id = %%s' % tagged_item_table,
328 '%s.%s = %s.object_id' % (qn(model._meta.db_table),
329 qn(model._meta.pk.column),
332 params=[content_type.pk, tag.pk],
335 def get_intersection_by_model(self, queryset_or_model, tags):
337 Create a ``QuerySet`` containing instances of the specified
338 model associated with *all* of the given list of tags.
340 tags = self.tag_model.get_tag_list(tags)
341 tag_count = len(tags)
342 queryset, model = get_queryset_and_model(queryset_or_model)
345 return model._default_manager.none()
347 model_table = qn(model._meta.db_table)
348 # This query selects the ids of all objects which have all the
352 FROM %(model)s, %(tagged_item)s
353 WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
354 AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
355 AND %(model_pk)s = %(tagged_item)s.object_id
356 GROUP BY %(model_pk)s
357 HAVING COUNT(%(model_pk)s) = %(tag_count)s""" % {
358 'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
359 'model': model_table,
360 'tagged_item': qn(self.model._meta.db_table),
361 'content_type_id': ContentType.objects.get_for_model(model).pk,
362 'tag_id_placeholders': ','.join(['%s'] * tag_count),
363 'tag_count': tag_count,
366 cursor = connection.cursor()
367 cursor.execute(query, [tag.pk for tag in tags])
368 object_ids = [row[0] for row in cursor.fetchall()]
369 if len(object_ids) > 0:
370 return queryset.filter(pk__in=object_ids)
372 return model._default_manager.none()
374 def get_union_by_model(self, queryset_or_model, tags):
376 Create a ``QuerySet`` containing instances of the specified
377 model associated with *any* of the given list of tags.
379 tags = self.tag_model.get_tag_list(tags)
380 tag_count = len(tags)
381 queryset, model = get_queryset_and_model(queryset_or_model)
384 return model._default_manager.none()
386 model_table = qn(model._meta.db_table)
387 # This query selects the ids of all objects which have any of
391 FROM %(model)s, %(tagged_item)s
392 WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
393 AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
394 AND %(model_pk)s = %(tagged_item)s.object_id
395 GROUP BY %(model_pk)s""" % {
396 'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
397 'model': model_table,
398 'tagged_item': qn(self.model._meta.db_table),
399 'content_type_id': ContentType.objects.get_for_model(model).pk,
400 'tag_id_placeholders': ','.join(['%s'] * tag_count),
403 cursor = connection.cursor()
404 cursor.execute(query, [tag.pk for tag in tags])
405 object_ids = [row[0] for row in cursor.fetchall()]
406 if len(object_ids) > 0:
407 return queryset.filter(pk__in=object_ids)
409 return model._default_manager.none()
411 def get_related(self, obj, queryset_or_model, num=None):
413 Retrieve a list of instances of the specified model which share
414 tags with the model instance ``obj``, ordered by the number of
415 shared tags in descending order.
417 If ``num`` is given, a maximum of ``num`` instances will be
420 queryset, model = get_queryset_and_model(queryset_or_model)
421 model_table = qn(model._meta.db_table)
422 content_type = ContentType.objects.get_for_model(obj)
423 related_content_type = ContentType.objects.get_for_model(model)
425 SELECT %(model_pk)s, COUNT(related_tagged_item.object_id) AS %(count)s
426 FROM %(model)s, %(tagged_item)s, %(tag)s, %(tagged_item)s related_tagged_item
427 WHERE %(tagged_item)s.object_id = %%s
428 AND %(tagged_item)s.content_type_id = %(content_type_id)s
429 AND %(tag)s.id = %(tagged_item)s.tag_id
430 AND related_tagged_item.content_type_id = %(related_content_type_id)s
431 AND related_tagged_item.tag_id = %(tagged_item)s.tag_id
432 AND %(model_pk)s = related_tagged_item.object_id"""
433 if content_type.pk == related_content_type.pk:
434 # Exclude the given instance itself if determining related
435 # instances for the same model.
437 AND related_tagged_item.object_id != %(tagged_item)s.object_id"""
439 GROUP BY %(model_pk)s
440 ORDER BY %(count)s DESC
443 'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
444 'count': qn('count'),
445 'model': model_table,
446 'tagged_item': qn(self.model._meta.db_table),
447 'tag': qn(self.model._meta.get_field('tag').rel.to._meta.db_table),
448 'content_type_id': content_type.pk,
449 'related_content_type_id': related_content_type.pk,
450 'limit_offset': num is not None and connection.ops.limit_offset_sql(num) or '',
453 cursor = connection.cursor()
454 cursor.execute(query, [obj.pk])
455 object_ids = [row[0] for row in cursor.fetchall()]
456 if len(object_ids) > 0:
457 # Use in_bulk here instead of an id__in lookup, because id__in would
458 # clobber the ordering.
459 object_dict = queryset.in_bulk(object_ids)
460 return [object_dict[object_id] for object_id in object_ids \
461 if object_id in object_dict]
469 def create_intermediary_table_model(model):
470 """Create an intermediary table model for the specific tag model"""
471 name = model.__name__ + 'Relation'
474 db_table = '%s_relation' % model._meta.db_table
475 unique_together = (('tag', 'content_type', 'object_id'),)
477 def obj_unicode(self):
479 return u'%s [%s]' % (self.content_type.get_object_for_this_type(pk=self.object_id), self.tag)
480 except ObjectDoesNotExist:
481 return u'<deleted> [%s]' % self.tag
483 # Set up a dictionary to simulate declarations within a class
485 '__module__': model.__module__,
487 'tag': models.ForeignKey(model, verbose_name=_('tag'), related_name='items'),
488 'content_type': models.ForeignKey(ContentType, verbose_name=_('content type')),
489 'object_id': models.PositiveIntegerField(_('object id'), db_index=True),
490 'content_object': generic.GenericForeignKey('content_type', 'object_id'),
491 '__unicode__': obj_unicode,
494 return type(name, (models.Model,), attrs)
497 class TagMeta(ModelBase):
498 "Metaclass for tag models (models inheriting from TagBase)."
499 def __new__(cls, name, bases, attrs):
500 model = super(TagMeta, cls).__new__(cls, name, bases, attrs)
501 if not model._meta.abstract:
502 # Create an intermediary table and register custom managers for concrete models
503 model.intermediary_table_model = create_intermediary_table_model(model)
504 TagManager(model.intermediary_table_model).contribute_to_class(model, 'objects')
505 TaggedItemManager(model).contribute_to_class(model.intermediary_table_model, 'objects')
509 class TagBase(models.Model):
510 """Abstract class to be inherited by model classes."""
511 __metaclass__ = TagMeta
517 def get_tag_list(tag_list):
519 Utility function for accepting tag input in a flexible manner.
521 You should probably override this method in your subclass.
523 if isinstance(tag_list, TagBase):