Commit f12660d4 by Alex Gaynor

initial work

parents
from django.contrib.contenttypes.models import ContentType
from django.db import models
from taggit.models import Tag, TaggedItem
from tagging.utils import require_instance_manager
class TaggableManager(object):
def __get__(self, instance, type):
manager = _TaggableManager()
manager.model = type
if instance is None:
manager.object_id = None
else:
manager.object_id = instance.pk
return manager
class _TaggableManager(models.Manager):
def get_query_set(self):
ct = ContentType.objects.get_for_model(self.model)
if self.object_id is not None:
return Tag.objects.filter(items__object_id=self.object_id,
items__content_type=ct)
else:
return Tag.objects.filter(items__content_type=ct)
@require_instance_manager
def add_tag(self, tag):
tag, _ = Tag.objects.get_or_create(name=tag)
TaggedItem.objects.create(object_id=self.object_id,
content_type=ContentType.objects.get_for_model(self.model), tag=tag)
@require_instance_manager
def add_tags(self, tags):
for tag in tags:
self.add_tag(tag)
@require_instance_manager
def set_tags(self, tags):
self.clear_tags()
self.add_tags(tags)
@require_instance_manager
def clear_tags(self):
TaggedItem.objects.filter(object_id=self.object_id,
content_type=ContentType.objects.get_for_model(self.model)).delete()
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.generic import GenericForeignKey
from django.db import models
class Tag(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class TaggedItem(models.Model):
object_id = models.IntegerField()
content_type = models.ForeignKey(ContentType)
content_object = GenericForeignKey()
tag = models.ForeignKey(Tag, related_name="items")
def __unicode__(self):
return "%s tagged with %" % (self.content_object, self.tag)
from functools import wraps
def split_tags(tags):
return [o.strip() for o in tags.split(',') if o.strip()]
def require_instance_manager(func):
@wraps
def inner(self, *args, **kwargs):
if self.object_id is None:
raise TypeError("Can't call %s with a non-instance manager" % func.__name__)
return func(self, *args, **kwargs)
return inner
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