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.db.models.query import QuerySet
12 from django.utils.translation import ugettext_lazy as _
13 from django.db.models.base import ModelBase
15 from newtagging.utils import get_tag_list, get_queryset_and_model
17 qn = connection.ops.quote_name
20 from django.db.models.query import parse_lookup
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
34 def update_tags(self, obj, tags):
36 Update tags associated with an object.
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)
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,
49 tag__in=tags_for_removal).delete()
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)
55 # def add_tag(self, obj, tag_name):
57 # Associates the given object with a tag.
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)
72 def get_for_object(self, obj):
74 Create a queryset matching all tags associated with the given
77 ctype = ContentType.objects.get_for_model(obj)
78 return self.filter(items__content_type__pk=ctype.pk,
79 items__object_id=obj.pk)
81 def _get_usage(self, model, counts=False, min_count=None, extra_joins=None, extra_criteria=None, params=None, extra=None):
83 Perform the custom SQL query for ``usage_for_model`` and
84 ``usage_for_queryset``.
86 if min_count is not None: counts = True
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()
92 if extra is None: extra = {}
95 extra_where = 'AND ' + ' AND '.join(extra['where'])
98 SELECT DISTINCT %(tag_columns)s%(count_sql)s
101 INNER JOIN %(tagged_item)s
102 ON %(tag)s.id = %(tagged_item)s.tag_id
104 ON %(tagged_item)s.object_id = %(model_pk)s
106 WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
109 GROUP BY %(tag)s.id, %(tag)s.name
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,
124 if min_count is not None:
125 min_count_sql = 'HAVING COUNT(%s) >= %%s' % model_pk
126 params.append(min_count)
128 cursor = connection.cursor()
129 cursor.execute(query % (extra_joins, extra_criteria, min_count_sql), params)
131 for row in cursor.fetchall():
132 t = self.model(*row[:len(self.model._meta.fields)])
134 t.count = row[len(self.model._meta.fields)]
138 def usage_for_model(self, model, counts=False, min_count=None, filters=None, extra=None):
140 Obtain a list of tags associated with instances of the given
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.
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``.
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.
156 if extra is None: extra = {}
157 if filters is None: filters = {}
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)
166 # pre-queryset-refactor
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)
179 def usage_for_queryset(self, queryset, counts=False, min_count=None, extra=None):
181 Obtain a list of tags associated with instances of a model
182 contained in the given queryset.
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.
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``.
193 raise AttributeError("'TagManager.usage_for_queryset' is not compatible with pre-queryset-refactor versions of Django.")
195 extra_joins = ' '.join(queryset.query.get_from_clause()[0][1:])
196 where, params = queryset.query.where.as_sql()
198 extra_criteria = 'AND %s' % where
201 return self._get_usage(queryset.model, counts, min_count, extra_joins, extra_criteria, params, extra)
203 def related_for_model(self, tags, model, counts=False, min_count=None, extra=None):
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.
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.
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``.
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()
222 if extra is None: extra = {}
225 extra_where = 'AND ' + ' AND '.join(extra['where'])
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
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
241 AND %(tag)s.id NOT IN (%(tag_id_placeholders)s)
243 GROUP BY %(tag)s.id, %(tag)s.name
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 '',
258 params = [tag.pk for tag in tags] * 2
259 if min_count is not None:
260 params.append(min_count)
262 cursor = connection.cursor()
263 cursor.execute(query, params)
265 for row in cursor.fetchall():
266 tag = self.model(*row[:len(self.model._meta.fields)])
268 tag.count = row[len(self.model._meta.fields)]
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)
277 class TaggedItemManager(models.Manager):
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
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``.
287 Once the queryset-refactor branch lands in trunk, this can be
288 tidied up significantly.
290 def get_by_model(self, queryset_or_model, tags):
292 Create a ``QuerySet`` containing instances of the specified
293 model associated with a given tag or list of tags.
295 tags = get_tag_list(tags)
296 tag_count = len(tags)
298 # No existing tags were given
299 queryset, model = get_queryset_and_model(queryset_or_model)
300 return model._default_manager.none()
302 # Optimisation for single tag - fall through to the simpler
306 return self.get_intersection_by_model(queryset_or_model, tags)
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],
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),
321 params=[content_type.pk, tag.pk],
324 def get_intersection_by_model(self, queryset_or_model, tags):
326 Create a ``QuerySet`` containing instances of the specified
327 model associated with *all* of the given list of tags.
329 tags = get_tag_list(tags)
330 tag_count = len(tags)
331 queryset, model = get_queryset_and_model(queryset_or_model)
334 return model._default_manager.none()
336 model_table = qn(model._meta.db_table)
337 # This query selects the ids of all objects which have all the
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,
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)
361 return model._default_manager.none()
363 def get_union_by_model(self, queryset_or_model, tags):
365 Create a ``QuerySet`` containing instances of the specified
366 model associated with *any* of the given list of tags.
368 tags = get_tag_list(tags)
369 tag_count = len(tags)
370 queryset, model = get_queryset_and_model(queryset_or_model)
373 return model._default_manager.none()
375 model_table = qn(model._meta.db_table)
376 # This query selects the ids of all objects which have any of
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),
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)
398 return model._default_manager.none()
400 def get_related(self, obj, queryset_or_model, num=None):
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.
406 If ``num`` is given, a maximum of ``num`` instances will be
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)
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.
426 AND related_tagged_item.object_id != %(tagged_item)s.object_id"""
428 GROUP BY %(model_pk)s
429 ORDER BY %(count)s DESC
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 '',
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]
458 def create_intermediary_table_model(model):
459 """Create an intermediary table model for the specific tag model"""
460 name = model.__name__ + 'Relation'
463 db_table = '%s_relation' % model._meta.db_table
464 unique_together = (('tag', 'content_type', 'object_id'),)
466 def obj_unicode(self):
467 return u'%s [%s]' % (self.content_type.get_object_for_this_type(pk=self.object_id), self.tag)
469 # Set up a dictionary to simulate declarations within a class
471 '__module__': model.__module__,
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,
480 return type(name, (models.Model,), attrs)
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')
495 class TagBase(models.Model):
496 """Abstract class to be inherited by model classes."""
497 __metaclass__ = TagMeta