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