Skip to content

Commit 8deb443

Browse files
committed
Merge branch 'feature/kwalitee' into develop
2 parents 3566a1a + fdf1d94 commit 8deb443

File tree

11 files changed

+368
-185
lines changed

11 files changed

+368
-185
lines changed

tagging/__init__.py

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,21 @@
1-
VERSION = (0, 3, 6, "final", 0)
1+
"""
2+
Django-tagging
3+
"""
4+
VERSION = (0, 3, 6, 'final', 0)
25

36

47
def get_version():
5-
if VERSION[3] == "final":
6-
return "%s.%s.%s" % (VERSION[0], VERSION[1], VERSION[2])
7-
elif VERSION[3] == "dev":
8+
if VERSION[3] == 'final':
9+
return '%s.%s.%s' % (VERSION[0], VERSION[1], VERSION[2])
10+
elif VERSION[3] == 'dev':
811
if VERSION[2] == 0:
9-
return "%s.%s.%s%s" % (VERSION[0], VERSION[1], VERSION[3], VERSION[4])
10-
return "%s.%s.%s.%s%s" % (VERSION[0], VERSION[1], VERSION[2], VERSION[3], VERSION[4])
12+
return '%s.%s.%s%s' % (VERSION[0], VERSION[1],
13+
VERSION[3], VERSION[4])
14+
return '%s.%s.%s.%s%s' % (VERSION[0], VERSION[1],
15+
VERSION[2], VERSION[3], VERSION[4])
1116
else:
12-
return "%s.%s.%s%s" % (VERSION[0], VERSION[1], VERSION[2], VERSION[3])
17+
return '%s.%s.%s%s' % (VERSION[0], VERSION[1],
18+
VERSION[2], VERSION[3])
1319

1420

1521
__version__ = get_version()
@@ -34,17 +40,20 @@ def register(model, tag_descriptor_attr='tags',
3440
from tagging.managers import ModelTaggedItemManager, TagDescriptor
3541

3642
if model in registry:
37-
raise AlreadyRegistered("The model '%s' has already been "
38-
"registered." % model._meta.object_name)
43+
raise AlreadyRegistered(
44+
"The model '%s' has already been registered." %
45+
model._meta.object_name)
3946
if hasattr(model, tag_descriptor_attr):
40-
raise AttributeError("'%s' already has an attribute '%s'. You must "
47+
raise AttributeError(
48+
"'%s' already has an attribute '%s'. You must "
4149
"provide a custom tag_descriptor_attr to register." % (
4250
model._meta.object_name,
4351
tag_descriptor_attr,
4452
)
4553
)
4654
if hasattr(model, tagged_item_manager_attr):
47-
raise AttributeError("'%s' already has an attribute '%s'. You must "
55+
raise AttributeError(
56+
"'%s' already has an attribute '%s'. You must "
4857
"provide a custom tagged_item_manager_attr to register." % (
4958
model._meta.object_name,
5059
tagged_item_manager_attr,
@@ -55,7 +64,8 @@ def register(model, tag_descriptor_attr='tags',
5564
setattr(model, tag_descriptor_attr, TagDescriptor())
5665

5766
# Add custom manager
58-
ModelTaggedItemManager().contribute_to_class(model, tagged_item_manager_attr)
67+
ModelTaggedItemManager().contribute_to_class(
68+
model, tagged_item_manager_attr)
5969

6070
# Finally register in registry
6171
registry.append(model)

tagging/fields.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,15 +59,17 @@ class Link(models.Model):
5959
self._set_instance_tag_cache(instance, '')
6060
else:
6161
self._set_instance_tag_cache(
62-
instance, edit_string_for_tags(Tag.objects.get_for_object(instance)))
62+
instance, edit_string_for_tags(
63+
Tag.objects.get_for_object(instance)))
6364
return self._get_instance_tag_cache(instance)
6465

6566
def __set__(self, instance, value):
6667
"""
6768
Set an object's tags.
6869
"""
6970
if instance is None:
70-
raise AttributeError(_('%s can only be set on instances.') % self.name)
71+
raise AttributeError(
72+
_('%s can only be set on instances.') % self.name)
7173
if settings.FORCE_LOWERCASE_TAGS and value is not None:
7274
value = value.lower()
7375
self._set_instance_tag_cache(instance, value)

tagging/generic.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,11 @@ def fetch_content_objects(tagged_items, select_related_for=None):
2929
for content_type_pk, object_pks in objects.iteritems():
3030
model = content_types[content_type_pk].model_class()
3131
if content_types[content_type_pk].model in select_related_for:
32-
objects[content_type_pk] = model._default_manager.select_related().in_bulk(object_pks)
32+
objects[content_type_pk] = model._default_manager.select_related(
33+
).in_bulk(object_pks)
3334
else:
34-
objects[content_type_pk] = model._default_manager.in_bulk(object_pks)
35+
objects[content_type_pk] = model._default_manager.in_bulk(
36+
object_pks)
3537

3638
# Set content types and content objects in the appropriate cache
3739
# attributes, so accessing the 'content_type' and 'object'

tagging/migrations/0001_initial.py

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
1-
from __future__ import unicode_literals
2-
3-
from django.db import models, migrations
1+
from django.db import models
2+
from django.db import migrations
43

54

65
class Migration(migrations.Migration):
@@ -13,8 +12,12 @@ class Migration(migrations.Migration):
1312
migrations.CreateModel(
1413
name='Tag',
1514
fields=[
16-
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
17-
('name', models.CharField(unique=True, max_length=50, verbose_name='name', db_index=True)),
15+
('id', models.AutoField(
16+
verbose_name='ID', serialize=False,
17+
auto_created=True, primary_key=True)),
18+
('name', models.CharField(
19+
unique=True, max_length=50,
20+
verbose_name='name', db_index=True)),
1821
],
1922
options={
2023
'ordering': ('name',),
@@ -25,10 +28,17 @@ class Migration(migrations.Migration):
2528
migrations.CreateModel(
2629
name='TaggedItem',
2730
fields=[
28-
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
29-
('object_id', models.PositiveIntegerField(verbose_name='object id', db_index=True)),
30-
('content_type', models.ForeignKey(verbose_name='content type', to='contenttypes.ContentType')),
31-
('tag', models.ForeignKey(related_name='items', verbose_name='tag', to='tagging.Tag')),
31+
('id', models.AutoField(
32+
verbose_name='ID', serialize=False,
33+
auto_created=True, primary_key=True)),
34+
('object_id', models.PositiveIntegerField(
35+
verbose_name='object id', db_index=True)),
36+
('content_type', models.ForeignKey(
37+
verbose_name='content type',
38+
to='contenttypes.ContentType')),
39+
('tag', models.ForeignKey(
40+
related_name='items', verbose_name='tag',
41+
to='tagging.Tag')),
3242
],
3343
options={
3444
'verbose_name': 'tagged item',

tagging/migrations/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"""
2+
Migrations for tagging
3+
"""

tagging/models.py

Lines changed: 57 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from django.contrib.contenttypes.models import ContentType
1010
try:
1111
from django.contrib.contenttypes.fields import GenericForeignKey
12-
except ImportError:
12+
except ImportError: # Django 1.8
1313
from django.contrib.contenttypes.generic import GenericForeignKey
1414

1515
from . import settings
@@ -28,6 +28,7 @@
2828
############
2929

3030
class TagManager(models.Manager):
31+
3132
def update_tags(self, obj, tag_names):
3233
"""
3334
Update tags associated with an object.
@@ -40,12 +41,13 @@ def update_tags(self, obj, tag_names):
4041
updated_tag_names = [t.lower() for t in updated_tag_names]
4142

4243
# Remove tags which no longer apply
43-
tags_for_removal = [tag for tag in current_tags \
44+
tags_for_removal = [tag for tag in current_tags
4445
if tag.name not in updated_tag_names]
4546
if len(tags_for_removal):
46-
TaggedItem._default_manager.filter(content_type__pk=ctype.pk,
47-
object_id=obj.pk,
48-
tag__in=tags_for_removal).delete()
47+
TaggedItem._default_manager.filter(
48+
content_type__pk=ctype.pk,
49+
object_id=obj.pk,
50+
tag__in=tags_for_removal).delete()
4951
# Add new tags
5052
current_tag_names = [tag.name for tag in current_tags]
5153
for tag_name in updated_tag_names:
@@ -59,9 +61,11 @@ def add_tag(self, obj, tag_name):
5961
"""
6062
tag_names = parse_tag_input(tag_name)
6163
if not len(tag_names):
62-
raise AttributeError(_('No tags were given: "%s".') % tag_name)
64+
raise AttributeError(
65+
_('No tags were given: "%s".') % tag_name)
6366
if len(tag_names) > 1:
64-
raise AttributeError(_('Multiple tags were given: "%s".') % tag_name)
67+
raise AttributeError(
68+
_('Multiple tags were given: "%s".') % tag_name)
6569
tag_name = tag_names[0]
6670
if settings.FORCE_LOWERCASE_TAGS:
6771
tag_name = tag_name.lower()
@@ -79,12 +83,14 @@ def get_for_object(self, obj):
7983
return self.filter(items__content_type__pk=ctype.pk,
8084
items__object_id=obj.pk)
8185

82-
def _get_usage(self, model, counts=False, min_count=None, extra_joins=None, extra_criteria=None, params=None):
86+
def _get_usage(self, model, counts=False, min_count=None,
87+
extra_joins=None, extra_criteria=None, params=None):
8388
"""
8489
Perform the custom SQL query for ``usage_for_model`` and
8590
``usage_for_queryset``.
8691
"""
87-
if min_count is not None: counts = True
92+
if min_count is not None:
93+
counts = True
8894

8995
model_table = qn(model._meta.db_table)
9096
model_pk = '%s.%s' % (model_table, qn(model._meta.pk.column))
@@ -116,7 +122,8 @@ def _get_usage(self, model, counts=False, min_count=None, extra_joins=None, extr
116122
params.append(min_count)
117123

118124
cursor = connection.cursor()
119-
cursor.execute(query % (extra_joins, extra_criteria, min_count_sql), params)
125+
cursor.execute(query % (extra_joins, extra_criteria, min_count_sql),
126+
params)
120127
tags = []
121128
for row in cursor.fetchall():
122129
t = self.model(*row[:2])
@@ -125,7 +132,8 @@ def _get_usage(self, model, counts=False, min_count=None, extra_joins=None, extr
125132
tags.append(t)
126133
return tags
127134

128-
def usage_for_model(self, model, counts=False, min_count=None, filters=None):
135+
def usage_for_model(self, model, counts=False, min_count=None,
136+
filters=None):
129137
"""
130138
Obtain a list of tags associated with instances of the given
131139
Model class.
@@ -143,7 +151,8 @@ def usage_for_model(self, model, counts=False, min_count=None, filters=None):
143151
of field lookups to be applied to the given Model as the
144152
``filters`` argument.
145153
"""
146-
if filters is None: filters = {}
154+
if filters is None:
155+
filters = {}
147156

148157
queryset = model._default_manager.filter()
149158
for f in filters.items():
@@ -185,7 +194,8 @@ def usage_for_queryset(self, queryset, counts=False, min_count=None):
185194
extra_criteria = 'AND %s' % where
186195
else:
187196
extra_criteria = ''
188-
return self._get_usage(queryset.model, counts, min_count, extra_joins, extra_criteria, params)
197+
return self._get_usage(queryset.model, counts, min_count,
198+
extra_joins, extra_criteria, params)
189199

190200
def related_for_model(self, tags, model, counts=False, min_count=None):
191201
"""
@@ -200,13 +210,16 @@ def related_for_model(self, tags, model, counts=False, min_count=None):
200210
greater than or equal to ``min_count`` will be returned.
201211
Passing a value for ``min_count`` implies ``counts=True``.
202212
"""
203-
if min_count is not None: counts = True
213+
if min_count is not None:
214+
counts = True
215+
204216
tags = get_tag_list(tags)
205217
tag_count = len(tags)
206218
tagged_item_table = qn(TaggedItem._meta.db_table)
207219
query = """
208220
SELECT %(tag)s.id, %(tag)s.name%(count_sql)s
209-
FROM %(tagged_item)s INNER JOIN %(tag)s ON %(tagged_item)s.tag_id = %(tag)s.id
221+
FROM %(tagged_item)s INNER JOIN %(tag)s ON
222+
%(tagged_item)s.tag_id = %(tag)s.id
210223
WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
211224
AND %(tagged_item)s.object_id IN
212225
(
@@ -223,12 +236,14 @@ def related_for_model(self, tags, model, counts=False, min_count=None):
223236
%(min_count_sql)s
224237
ORDER BY %(tag)s.name ASC""" % {
225238
'tag': qn(self.model._meta.db_table),
226-
'count_sql': counts and ', COUNT(%s.object_id)' % tagged_item_table or '',
239+
'count_sql': counts and ', COUNT(%s.object_id)' %
240+
tagged_item_table or '',
227241
'tagged_item': tagged_item_table,
228242
'content_type_id': ContentType.objects.get_for_model(model).pk,
229243
'tag_id_placeholders': ','.join(['%s'] * tag_count),
230244
'tag_count': tag_count,
231-
'min_count_sql': min_count is not None and ('HAVING COUNT(%s.object_id) >= %%s' % tagged_item_table) or '',
245+
'min_count_sql': min_count is not None and (
246+
'HAVING COUNT(%s.object_id) >= %%s' % tagged_item_table) or '',
232247
}
233248

234249
params = [tag.pk for tag in tags] * 2
@@ -274,6 +289,7 @@ def cloud_for_model(self, model, steps=4, distribution=LOGARITHMIC,
274289
min_count=min_count))
275290
return calculate_cloud(tags, steps, distribution)
276291

292+
277293
class TaggedItemManager(models.Manager):
278294
"""
279295
FIXME There's currently no way to get the ``GROUP BY`` and ``HAVING``
@@ -287,6 +303,7 @@ class TaggedItemManager(models.Manager):
287303
Now that the queryset-refactor branch is in the trunk, this can be
288304
tidied up significantly.
289305
"""
306+
290307
def get_by_model(self, queryset_or_model, tags):
291308
"""
292309
Create a ``QuerySet`` containing instances of the specified
@@ -412,7 +429,8 @@ def get_related(self, obj, queryset_or_model, num=None):
412429
related_content_type = ContentType.objects.get_for_model(model)
413430
query = """
414431
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
432+
FROM %(model)s, %(tagged_item)s, %(tag)s,
433+
%(tagged_item)s related_tagged_item
416434
WHERE %(tagged_item)s.object_id = %%s
417435
AND %(tagged_item)s.content_type_id = %(content_type_id)s
418436
AND %(tag)s.id = %(tagged_item)s.tag_id
@@ -448,10 +466,10 @@ def get_related(self, obj, queryset_or_model, num=None):
448466
cursor.execute(query, params)
449467
object_ids = [row[0] for row in cursor.fetchall()]
450468
if len(object_ids) > 0:
451-
# Use in_bulk here instead of an id__in lookup, because id__in would
452-
# clobber the ordering.
469+
# Use in_bulk here instead of an id__in lookup,
470+
# because id__in would clobber the ordering.
453471
object_dict = queryset.in_bulk(object_ids)
454-
return [object_dict[object_id] for object_id in object_ids \
472+
return [object_dict[object_id] for object_id in object_ids
455473
if object_id in object_dict]
456474
else:
457475
return []
@@ -466,7 +484,9 @@ class Tag(models.Model):
466484
"""
467485
A tag.
468486
"""
469-
name = models.CharField(_('name'), max_length=50, unique=True, db_index=True)
487+
name = models.CharField(
488+
_('name'), max_length=50,
489+
unique=True, db_index=True)
470490

471491
objects = TagManager()
472492

@@ -484,10 +504,21 @@ class TaggedItem(models.Model):
484504
"""
485505
Holds the relationship between a tag and the item being tagged.
486506
"""
487-
tag = models.ForeignKey(Tag, 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-
object = GenericForeignKey('content_type', 'object_id')
507+
tag = models.ForeignKey(
508+
Tag,
509+
verbose_name=_('tag'),
510+
related_name='items')
511+
512+
content_type = models.ForeignKey(
513+
ContentType,
514+
verbose_name=_('content type'))
515+
516+
object_id = models.PositiveIntegerField(
517+
_('object id'),
518+
db_index=True)
519+
520+
object = GenericForeignKey(
521+
'content_type', 'object_id')
491522

492523
objects = TaggedItemManager()
493524

0 commit comments

Comments
 (0)