-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Update tags with optional replace existing tags flag. #3
Open
bocribbz
wants to merge
6
commits into
jlward:master
Choose a base branch
from
bocribbz:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
cd19f3b
pep fixes
bocribbz c08a30a
more pep fixes
bocribbz e04bd25
add test to check tags update without replace existing tags
bocribbz 890d9d1
update logic to avoid resetting tags if doenst replace existing ones
bocribbz 68575e2
drop support for django <1.7
bocribbz bde81f5
removing unsuported version from travis runs
bocribbz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,22 +1,20 @@ | ||
""" | ||
Models and managers for generic tagging. | ||
""" | ||
# Python 2.3 compatibility | ||
try: | ||
set | ||
except NameError: | ||
from sets import Set as set | ||
|
||
from django.contrib.contenttypes import generic | ||
from django.contrib.contenttypes.models import ContentType | ||
from django.conf import settings | ||
|
||
from django.db import connection, models | ||
from django.db.models.query import QuerySet | ||
from django.utils.translation import ugettext_lazy as _ | ||
|
||
from tagging.settings import DEFAULT_FORCE_LOWERCASE_TAGS | ||
from tagging.utils import calculate_cloud, get_tag_list, get_queryset_and_model, parse_tag_input | ||
from tagging.utils import ( | ||
calculate_cloud, | ||
get_tag_list, | ||
get_queryset_and_model, | ||
parse_tag_input, | ||
) | ||
from tagging.utils import LOGARITHMIC | ||
|
||
qn = connection.ops.quote_name | ||
|
@@ -25,25 +23,35 @@ | |
# Managers # | ||
############ | ||
|
||
|
||
class TagManager(models.Manager): | ||
def update_tags(self, obj, tag_names): | ||
def update_tags(self, obj, tag_names, replace_existing=True): | ||
""" | ||
Update tags associated with an object. | ||
""" | ||
ctype = ContentType.objects.get_for_model(obj) | ||
current_tags = list(self.filter(items__content_type__pk=ctype.pk, | ||
items__object_id=obj.pk)) | ||
updated_tag_names = parse_tag_input(tag_names) | ||
if getattr(settings, 'FORCE_LOWERCASE_TAGS', DEFAULT_FORCE_LOWERCASE_TAGS): | ||
force_lowercase = getattr( | ||
settings, | ||
'FORCE_LOWERCASE_TAGS', | ||
DEFAULT_FORCE_LOWERCASE_TAGS, | ||
) | ||
if force_lowercase: | ||
updated_tag_names = [t.lower() for t in updated_tag_names] | ||
|
||
# Remove tags which no longer apply | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. actual change |
||
tags_for_removal = [tag for tag in current_tags \ | ||
if tag.name not in updated_tag_names] | ||
if len(tags_for_removal): | ||
TaggedItem._default_manager.filter(content_type__pk=ctype.pk, | ||
object_id=obj.pk, | ||
tag__in=tags_for_removal).delete() | ||
if replace_existing: | ||
# Remove tags which no longer apply | ||
tags_for_removal = [tag for tag in current_tags | ||
if tag.name not in updated_tag_names] | ||
if len(tags_for_removal): | ||
TaggedItem._default_manager.filter( | ||
content_type__pk=ctype.pk, | ||
object_id=obj.pk, | ||
tag__in=tags_for_removal, | ||
).delete() | ||
|
||
# Add new tags | ||
current_tag_names = [tag.name for tag in current_tags] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. bellow are pep8 fixes. check the tests ;) |
||
for tag_name in updated_tag_names: | ||
|
@@ -59,9 +67,16 @@ def add_tag(self, obj, tag_name): | |
if not len(tag_names): | ||
raise AttributeError(_('No tags were given: "%s".') % tag_name) | ||
if len(tag_names) > 1: | ||
raise AttributeError(_('Multiple tags were given: "%s".') % tag_name) | ||
raise AttributeError( | ||
_('Multiple tags were given: "%s".') % tag_name | ||
) | ||
tag_name = tag_names[0] | ||
if getattr(settings, 'FORCE_LOWERCASE_TAGS', DEFAULT_FORCE_LOWERCASE_TAGS): | ||
force_lowercase = getattr( | ||
settings, | ||
'FORCE_LOWERCASE_TAGS', | ||
DEFAULT_FORCE_LOWERCASE_TAGS, | ||
) | ||
if force_lowercase: | ||
tag_name = tag_name.lower() | ||
tag, created = self.get_or_create(name=tag_name) | ||
ctype = ContentType.objects.get_for_model(obj) | ||
|
@@ -77,12 +92,21 @@ def get_for_object(self, obj): | |
return self.filter(items__content_type__pk=ctype.pk, | ||
items__object_id=obj.pk) | ||
|
||
def _get_usage(self, model, counts=False, min_count=None, extra_joins=None, extra_criteria=None, params=None): | ||
def _get_usage( | ||
self, | ||
model, | ||
counts=False, | ||
min_count=None, | ||
extra_joins=None, | ||
extra_criteria=None, | ||
params=None, | ||
): | ||
""" | ||
Perform the custom SQL query for ``usage_for_model`` and | ||
``usage_for_queryset``. | ||
""" | ||
if min_count is not None: counts = True | ||
if min_count is not None: | ||
counts = True | ||
|
||
model_table = qn(model._meta.db_table) | ||
model_pk = '%s.%s' % (model_table, qn(model._meta.pk.column)) | ||
|
@@ -114,7 +138,10 @@ def _get_usage(self, model, counts=False, min_count=None, extra_joins=None, extr | |
params.append(min_count) | ||
|
||
cursor = connection.cursor() | ||
cursor.execute(query % (extra_joins, extra_criteria, min_count_sql), params) | ||
cursor.execute( | ||
query % (extra_joins, extra_criteria, min_count_sql), | ||
params | ||
) | ||
tags = [] | ||
for row in cursor.fetchall(): | ||
t = self.model(*row[:2]) | ||
|
@@ -123,7 +150,13 @@ def _get_usage(self, model, counts=False, min_count=None, extra_joins=None, extr | |
tags.append(t) | ||
return tags | ||
|
||
def usage_for_model(self, model, counts=False, min_count=None, filters=None): | ||
def usage_for_model( | ||
self, | ||
model, | ||
counts=False, | ||
min_count=None, | ||
filters=None | ||
): | ||
""" | ||
Obtain a list of tags associated with instances of the given | ||
Model class. | ||
|
@@ -141,7 +174,8 @@ def usage_for_model(self, model, counts=False, min_count=None, filters=None): | |
of field lookups to be applied to the given Model as the | ||
``filters`` argument. | ||
""" | ||
if filters is None: filters = {} | ||
if filters is None: | ||
filters = {} | ||
|
||
queryset = model._default_manager.filter() | ||
for f in filters.items(): | ||
|
@@ -183,7 +217,14 @@ def usage_for_queryset(self, queryset, counts=False, min_count=None): | |
extra_criteria = 'AND %s' % where | ||
else: | ||
extra_criteria = '' | ||
return self._get_usage(queryset.model, counts, min_count, extra_joins, extra_criteria, params) | ||
return self._get_usage( | ||
queryset.model, | ||
counts, | ||
min_count, | ||
extra_joins, | ||
extra_criteria, | ||
params, | ||
) | ||
|
||
def related_for_model(self, tags, model, counts=False, min_count=None): | ||
""" | ||
|
@@ -198,13 +239,15 @@ def related_for_model(self, tags, model, counts=False, min_count=None): | |
greater than or equal to ``min_count`` will be returned. | ||
Passing a value for ``min_count`` implies ``counts=True``. | ||
""" | ||
if min_count is not None: counts = True | ||
if min_count is not None: | ||
counts = True | ||
tags = get_tag_list(tags) | ||
tag_count = len(tags) | ||
tagged_item_table = qn(TaggedItem._meta.db_table) | ||
query = """ | ||
SELECT %(tag)s.id, %(tag)s.name%(count_sql)s | ||
FROM %(tagged_item)s INNER JOIN %(tag)s ON %(tagged_item)s.tag_id = %(tag)s.id | ||
FROM %(tagged_item)s | ||
INNER JOIN %(tag)s ON %(tagged_item)s.tag_id = %(tag)s.id | ||
WHERE %(tagged_item)s.content_type_id = %(content_type_id)s | ||
AND %(tagged_item)s.object_id IN | ||
( | ||
|
@@ -221,12 +264,20 @@ def related_for_model(self, tags, model, counts=False, min_count=None): | |
%(min_count_sql)s | ||
ORDER BY %(tag)s.name ASC""" % { | ||
'tag': qn(self.model._meta.db_table), | ||
'count_sql': counts and ', COUNT(%s.object_id)' % tagged_item_table or '', | ||
'count_sql': ( | ||
counts and | ||
', COUNT(%s.object_id)' % tagged_item_table or | ||
'' | ||
), | ||
'tagged_item': tagged_item_table, | ||
'content_type_id': ContentType.objects.get_for_model(model).pk, | ||
'tag_id_placeholders': ','.join(['%s'] * tag_count), | ||
'tag_count': tag_count, | ||
'min_count_sql': min_count is not None and ('HAVING COUNT(%s.object_id) >= %%s' % tagged_item_table) or '', | ||
'min_count_sql': ( | ||
min_count is not None and | ||
('HAVING COUNT(%s.object_id) >= %%s' % tagged_item_table) or | ||
'' | ||
), | ||
} | ||
|
||
params = [tag.pk for tag in tags] * 2 | ||
|
@@ -272,6 +323,7 @@ def cloud_for_model(self, model, steps=4, distribution=LOGARITHMIC, | |
min_count=min_count)) | ||
return calculate_cloud(tags, steps, distribution) | ||
|
||
|
||
class TaggedItemManager(models.Manager): | ||
""" | ||
FIXME There's currently no way to get the ``GROUP BY`` and ``HAVING`` | ||
|
@@ -410,7 +462,12 @@ def get_related(self, obj, queryset_or_model, num=None): | |
related_content_type = ContentType.objects.get_for_model(model) | ||
query = """ | ||
SELECT %(model_pk)s, COUNT(related_tagged_item.object_id) AS %(count)s | ||
FROM %(model)s, %(tagged_item)s, %(tag)s, %(tagged_item)s related_tagged_item | ||
FROM | ||
%(model)s, | ||
%(tagged_item)s, | ||
%(tag)s, | ||
%(tagged_item)s | ||
related_tagged_item | ||
WHERE %(tagged_item)s.object_id = %%s | ||
AND %(tagged_item)s.content_type_id = %(content_type_id)s | ||
AND %(tag)s.id = %(tagged_item)s.tag_id | ||
|
@@ -446,10 +503,11 @@ def get_related(self, obj, queryset_or_model, num=None): | |
cursor.execute(query, params) | ||
object_ids = [row[0] for row in cursor.fetchall()] | ||
if len(object_ids) > 0: | ||
# Use in_bulk here instead of an id__in lookup, because id__in would | ||
# Use in_bulk here instead of an id__in lookup, | ||
# because id__in would | ||
# clobber the ordering. | ||
object_dict = queryset.in_bulk(object_ids) | ||
return [object_dict[object_id] for object_id in object_ids \ | ||
return [object_dict[object_id] for object_id in object_ids | ||
if object_id in object_dict] | ||
else: | ||
return [] | ||
|
@@ -458,11 +516,17 @@ def get_related(self, obj, queryset_or_model, num=None): | |
# Models # | ||
########## | ||
|
||
|
||
class Tag(models.Model): | ||
""" | ||
A tag. | ||
""" | ||
name = models.CharField(_('name'), max_length=50, unique=True, db_index=True) | ||
name = models.CharField( | ||
_('name'), | ||
max_length=50, | ||
unique=True, | ||
db_index=True, | ||
) | ||
|
||
objects = TagManager() | ||
|
||
|
@@ -474,14 +538,18 @@ class Meta: | |
def __unicode__(self): | ||
return self.name | ||
|
||
|
||
class TaggedItem(models.Model): | ||
""" | ||
Holds the relationship between a tag and the item being tagged. | ||
""" | ||
tag = models.ForeignKey(Tag, verbose_name=_('tag'), related_name='items') | ||
content_type = models.ForeignKey(ContentType, verbose_name=_('content type')) | ||
object_id = models.PositiveIntegerField(_('object id'), db_index=True) | ||
object = generic.GenericForeignKey('content_type', 'object_id') | ||
tag = models.ForeignKey(Tag, verbose_name=_('tag'), related_name='items') | ||
content_type = models.ForeignKey( | ||
ContentType, | ||
verbose_name=_('content type'), | ||
) | ||
object_id = models.PositiveIntegerField(_('object id'), db_index=True) | ||
object = generic.GenericForeignKey('content_type', 'object_id') | ||
|
||
objects = TaggedItemManager() | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
actual change