Skip to content

Instantly share code, notes, and snippets.

@lovevn
Forked from smilesh/model_for_taggit.py
Last active August 29, 2015 14:21
Show Gist options
  • Save lovevn/3a7e6fe0354618469ff7 to your computer and use it in GitHub Desktop.
Save lovevn/3a7e6fe0354618469ff7 to your computer and use it in GitHub Desktop.
from django.db import models
from django.utils.translation import ugettext_lazy as _
from taggit.models import Tag, ItemBase
# it is required to support unicode tags slugify
# https://github.com/mozilla/unicode-slugify
from slugify import slugify as default_slugify
class UserContents(models.Model):
id = models.CharField("Content ID", max_length=50, primary_key=True, blank=True)
title = models.CharField("Content Title", max_length=140, default='', null=True, blank=True)
description = models.TextField("Content Description", max_length=2000, default='', null=True, blank=True)
# it provides custom TaggedItem by through attribute
tags = TaggableManager(through=UserContentsTaggedItem)
datetime_modified = models.DateTimeField(null=False, auto_now=True)
datetime_created = models.DateTimeField(null=False, blank=True)
class TagExtended(Tag):
# store created datetime with tag to analyze tagging data
datetime_created = models.DateTimeField(auto_now_add = True)
# inherit slugify from TagBase
def slugify(self, tag, i=None):
slug = default_slugify(tag)
if i is not None:
slug += "_%d" % i
return slug
class UserContentsTaggedItem(ItemBase):
tag = models.ForeignKey('TagExtended', related_name="%(app_label)s_%(class)s_tagged_items")
# store created datetime with tagged contents to analyze tagging data
datetime_created = models.DateTimeField(auto_now_add = True)
# it supports string pk of content_object
object_id = models.CharField(verbose_name=_('Object id'), max_length=100, db_index=True)
content_object = models.ForeignKey(UserContents)
@classmethod
def tags_for(cls, model, instance=None):
if instance is not None:
return cls.tag_model().objects.filter(**{
'%s__content_object' % cls.tag_relname(): instance
})
return cls.tag_model().objects.filter(**{
'%s__content_object__isnull' % cls.tag_relname(): False
}).distinct()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment