CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-django-taggit

A reusable Django application for simple tagging with comprehensive manager and form support.

Pending
Overview
Eval results
Files

model-integration.mddocs/

Model Integration

Core functionality for adding tagging capabilities to Django models using the TaggableManager field. The TaggableManager provides a simple interface for adding comprehensive tagging functionality to any Django model.

Capabilities

TaggableManager Field

The main entry point for adding tagging functionality to Django models. Acts as a Django field that provides access to tag operations.

class TaggableManager:
    """
    Field for adding tagging functionality to Django models.
    
    Parameters:
    - verbose_name (str): Human-readable name for the field
    - help_text (str): Help text shown in forms and admin
    - through (Model): Custom through model for tag relationships
    - blank (bool): Whether field is required in forms
    - related_name (str): Name for reverse relation
    - to (Model): Custom tag model to use
    - ordering (list): Default ordering for tags
    - manager (class): Custom manager class for tag operations
    """
    def __init__(
        self,
        verbose_name="Tags",
        help_text="A comma-separated list of tags.",
        through=None,
        blank=False,
        related_name=None,
        to=None,
        ordering=None,
        manager=None
    ):
        """Initialize TaggableManager with configuration options."""
    
    def __get__(self, instance, model):
        """
        Return the tag manager for the instance or model.
        
        Parameters:
        - instance: Model instance (None for class access)
        - model: Model class
        
        Returns:
        _TaggableManager: Manager instance for tag operations
        """
    
    def formfield(self, form_class=None, **kwargs):
        """
        Return a form field for this manager.
        
        Parameters:
        - form_class: Custom form field class (defaults to TagField)
        - **kwargs: Additional form field arguments
        
        Returns:
        TagField: Form field for tag input
        """
    
    def save_form_data(self, instance, value):
        """
        Save form data to the instance's tags.
        
        Parameters:
        - instance: Model instance
        - value: Form data (list of tag names or tag string)
        """
    
    def value_from_object(self, obj):
        """
        Get tag values from a model instance for forms.
        
        Parameters:
        - obj: Model instance
        
        Returns:
        list: List of Tag objects
        """

Basic Model Setup

Simple integration with default settings using the built-in Tag and TaggedItem models.

from django.db import models
from taggit.managers import TaggableManager

class Article(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    tags = TaggableManager()

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    tags = TaggableManager(blank=True, help_text="Optional product tags")

Custom Through Models

Using custom through models for additional fields on tag relationships.

from taggit.models import TaggedItemBase

class TaggedFood(TaggedItemBase):
    content_object = models.ForeignKey('Food', on_delete=models.CASCADE)
    added_by = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    date_added = models.DateTimeField(auto_now_add=True)

class Food(models.Model):
    name = models.CharField(max_length=100)
    tags = TaggableManager(through=TaggedFood)

Custom Tag Models

Using custom tag models with additional fields.

from taggit.models import TagBase

class CustomTag(TagBase):
    description = models.TextField(blank=True)
    color = models.CharField(max_length=7, default='#000000')
    
class Item(models.Model):
    name = models.CharField(max_length=100)
    tags = TaggableManager(to=CustomTag)

UUID Support

Support for models with UUID primary keys using the UUID-specific base classes.

import uuid
from django.db import models
from taggit.models import GenericUUIDTaggedItemBase

class UUIDTaggedItem(GenericUUIDTaggedItemBase):
    # Automatically handles UUID object_id field
    pass

class UUIDModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=100)
    tags = TaggableManager(through=UUIDTaggedItem)

Multiple TaggableManagers

Using multiple tag managers on a single model for different types of tags.

from taggit.managers import TaggableManager
from taggit.models import TaggedItemBase

class TaggedArticleCategory(TaggedItemBase):
    content_object = models.ForeignKey('Article', on_delete=models.CASCADE)

class TaggedArticleKeyword(TaggedItemBase):
    content_object = models.ForeignKey('Article', on_delete=models.CASCADE)

class Article(models.Model):
    title = models.CharField(max_length=200)
    categories = TaggableManager(through=TaggedArticleCategory, related_name='category_articles')
    keywords = TaggableManager(through=TaggedArticleKeyword, related_name='keyword_articles')

Manager Access

Accessing tag managers at the model class level for querying and filtering.

# Access manager for model-level operations
Model.tags.all()  # All tags used by any instance of Model
Model.tags.most_common()  # Most commonly used tags across all instances

# Manager methods available at model level
def all(): ...
def most_common(min_count=None, extra_filters=None): ...
def filter(**kwargs): ...

Prefetching and Performance

Optimizing tag queries using Django's prefetch_related functionality.

# Prefetch tags to avoid N+1 queries
articles = Article.objects.prefetch_related('tags').all()

# Custom prefetch with filtering
from django.db.models import Prefetch
articles = Article.objects.prefetch_related(
    Prefetch('tags', queryset=Tag.objects.filter(name__startswith='tech'))
)

# Prefetch tagged items for reverse lookups
tags = Tag.objects.prefetch_related('tagged_items').all()

Configuration Options

Settings

Django settings that affect tagging behavior globally.

# settings.py

# Case-insensitive tag matching
TAGGIT_CASE_INSENSITIVE = True

# Strip unicode when creating slugs
TAGGIT_STRIP_UNICODE_WHEN_SLUGIFYING = True

# Custom tag parsing function
TAGGIT_TAGS_FROM_STRING = 'myapp.utils.custom_parse_tags'

# Custom tag formatting function
TAGGIT_STRING_FROM_TAGS = 'myapp.utils.custom_format_tags'

Field Options

Options available when defining TaggableManager fields.

class MyModel(models.Model):
    # Basic field
    tags = TaggableManager()
    
    # Optional field with custom help text
    categories = TaggableManager(
        blank=True,
        help_text="Categorize this item",
        verbose_name="Categories"
    )
    
    # Custom ordering
    ordered_tags = TaggableManager(
        ordering=['name'],  # Alphabetical order
        related_name='ordered_items'
    )

Install with Tessl CLI

npx tessl i tessl/pypi-django-taggit

docs

admin-interface.md

form-integration.md

index.md

model-integration.md

rest-framework.md

tag-operations.md

utilities-management.md

view-helpers.md

tile.json