Commit bb3dc0a9 by Daniel Hahler Committed by Florian Apolloner

Raise ValueError with invalid types in `add`

parent b953b74d
...@@ -133,12 +133,17 @@ class _TaggableManager(models.Manager): ...@@ -133,12 +133,17 @@ class _TaggableManager(models.Manager):
@require_instance_manager @require_instance_manager
def add(self, *tags): def add(self, *tags):
str_tags = set([ str_tags = set()
t tag_objs = set()
for t in tags for t in tags:
if not isinstance(t, self.through.tag_model()) if isinstance(t, self.through.tag_model()):
]) tag_objs.add(t)
tag_objs = set(tags) - str_tags elif isinstance(t, six.string_types):
str_tags.add(t)
else:
raise ValueError("Cannot add {0} ({1}). Expected {2} or str.".format(
t, type(t), type(self.through.tag_model())))
# If str_tags has 0 elements Django actually optimizes that to not do a # If str_tags has 0 elements Django actually optimizes that to not do a
# query. Malcolm is very smart. # query. Malcolm is very smart.
existing = self.through.tag_model().objects.filter( existing = self.through.tag_model().objects.filter(
......
...@@ -86,6 +86,14 @@ class TagModelTestCase(BaseTaggingTransactionTestCase): ...@@ -86,6 +86,14 @@ class TagModelTestCase(BaseTaggingTransactionTestCase):
"category-awesome-1" "category-awesome-1"
], attr="slug") ], attr="slug")
def test_integers(self):
"""Adding an integer as a tag should raise a ValueError (#237)."""
apple = self.food_model.objects.create(name="apple")
with self.assertRaisesRegexp(ValueError, (
r"Cannot add 1 \(<(type|class) 'int'>\). "
r"Expected <class 'django.db.models.base.ModelBase'> or str.")):
apple.tags.add(1)
class TagModelDirectTestCase(TagModelTestCase): class TagModelDirectTestCase(TagModelTestCase):
food_model = DirectFood food_model = DirectFood
tag_model = Tag tag_model = Tag
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment