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

tag-operations.mddocs/

Tag Operations

Methods for adding, removing, querying, and managing tags on model instances. These operations are available through the TaggableManager and provide comprehensive functionality for tag manipulation and retrieval.

Capabilities

Adding Tags

Add one or more tags to a model instance, with support for both string tags and Tag objects.

def add(*tags, through_defaults=None, tag_kwargs=None, **kwargs):
    """
    Add tags to the instance.
    
    Parameters:
    - *tags: Tag names (strings) or Tag objects to add
    - through_defaults (dict): Default values for through model fields
    - tag_kwargs (dict): Additional parameters for tag creation
    - **kwargs: Additional parameters passed to tag creation
    
    Returns:
    None
    """
# Add string tags
article.tags.add("python", "django", "web development")

# Add Tag objects
python_tag = Tag.objects.get(name="python")
article.tags.add(python_tag)

# Mix strings and Tag objects
article.tags.add("javascript", python_tag, "tutorial")

# Add with through model defaults (for custom through models)
article.tags.add("featured", through_defaults={'priority': 5})

# Add with tag creation parameters
article.tags.add("Python", tag_kwargs={'slug': 'python-lang'})

Removing Tags

Remove specific tags from a model instance.

def remove(*tags):
    """
    Remove tags from the instance.
    
    Parameters:
    - *tags: Tag names (strings) to remove
    
    Returns:
    None
    """
# Remove specific tags
article.tags.remove("outdated", "deprecated")

# Remove single tag
article.tags.remove("draft")

Clearing Tags

Remove all tags from a model instance.

def clear():
    """
    Remove all tags from the instance.
    
    Returns:
    None
    """
# Remove all tags
article.tags.clear()

Setting Tags

Replace all existing tags with a new set of tags.

def set(tags, *, through_defaults=None, **kwargs):
    """
    Set the instance's tags to the given tags, replacing all existing tags.
    
    Parameters:
    - tags: List of tag names (strings) or Tag objects
    - through_defaults (dict): Default values for through model fields
    - clear (bool): Whether to clear existing tags first (default: False)
    - tag_kwargs (dict): Additional parameters for tag creation
    
    Returns:
    None
    """
# Replace all tags with new set
article.tags.set(["python", "tutorial", "beginner"])

# Clear and set (explicit clear)
article.tags.set(["advanced", "expert"], clear=True)

# Set with through model defaults
article.tags.set(["featured"], through_defaults={'priority': 10})

Querying Tags

Retrieve tags associated with an instance in various formats.

def all():
    """
    Get all tags for this instance as a QuerySet.
    
    Returns:
    QuerySet: QuerySet of Tag objects
    """

def names():
    """
    Get tag names as a list of strings.
    
    Returns:
    list: List of tag names as strings
    """

def slugs():
    """
    Get tag slugs as a list of strings.
    
    Returns:
    list: List of tag slugs as strings
    """

def values_list(*fields, flat=False):
    """
    Get tag field values as a list.
    
    Parameters:
    - *fields: Field names to retrieve
    - flat (bool): If True and only one field, return flat list
    
    Returns:
    list: List of tuples or flat list if flat=True
    """

def get_queryset(extra_filters=None):
    """
    Get the base queryset for tags.
    
    Parameters:
    - extra_filters (dict): Additional filter conditions
    
    Returns:
    QuerySet: Filtered tag queryset
    """
# Get all tags as QuerySet
all_tags = article.tags.all()
for tag in all_tags:
    print(tag.name, tag.slug)

# Get just tag names
tag_names = article.tags.names()
# Returns: ['python', 'django', 'tutorial']

# Get tag slugs
tag_slugs = article.tags.slugs()
# Returns: ['python', 'django', 'tutorial']

# Get specific field values
tag_ids = article.tags.values_list('id', flat=True)
# Returns: [1, 5, 12]

Most Common Tags

Find the most frequently used tags, with optional filtering and minimum count requirements.

def most_common(min_count=None, extra_filters=None):
    """
    Get tags ordered by usage frequency.
    
    Parameters:
    - min_count (int): Minimum number of times tag must be used
    - extra_filters (dict): Additional filters to apply
    
    Returns:
    QuerySet of tags annotated with 'num_times' field
    """
# Get most common tags for this instance's model
common_tags = Article.tags.most_common()
for tag in common_tags:
    print(f"{tag.name}: {tag.num_times} times")

# Minimum usage count
popular_tags = Article.tags.most_common(min_count=5)

# With additional filtering
recent_common = Article.tags.most_common(
    extra_filters={'tagged_items__content_object__created_at__gte': last_month}
)

Similar Objects

Find objects that share tags with the current instance.

def similar_objects():
    """
    Find objects that share tags with this instance.
    
    Returns:
    List of objects with 'similar_tags' attribute indicating shared tag count
    """
# Find articles with similar tags
similar_articles = article.tags.similar_objects()
for similar in similar_articles:
    print(f"{similar.title}: {similar.similar_tags} shared tags")

Filtering and Querying

Query models based on their tags using Django's ORM.

# Filter by exact tag name
python_articles = Article.objects.filter(tags__name="python")

# Filter by multiple tags (OR)
web_articles = Article.objects.filter(tags__name__in=["python", "javascript"])

# Filter by multiple tags (AND) - articles that have both tags
both_tags = Article.objects.filter(tags__name="python").filter(tags__name="django")

# Filter by tag slug
articles = Article.objects.filter(tags__slug="web-development")

# Exclude certain tags
non_tutorial = Article.objects.exclude(tags__name="tutorial")

# Count articles per tag
from django.db.models import Count
tag_counts = Tag.objects.annotate(
    article_count=Count('tagged_items')
).filter(article_count__gt=0)

Bulk Operations

Efficient operations for working with multiple objects or large datasets.

# Bulk add tags to multiple objects
articles = Article.objects.filter(category="programming")
for article in articles:
    article.tags.add("programming")
    
# Use bulk operations for better performance
from django.db import transaction
with transaction.atomic():
    for article in articles:
        article.tags.add("bulk-tagged")

# Get all tags for multiple objects
article_ids = [1, 2, 3, 4, 5]
all_tags = Tag.objects.filter(
    tagged_items__content_type=ContentType.objects.get_for_model(Article),
    tagged_items__object_id__in=article_ids
).distinct()

Tag Statistics

Analyze tag usage patterns and statistics.

# Count total tagged items for a tag
tag = Tag.objects.get(name="python")
usage_count = tag.tagged_items.count()

# Get tag usage over time
from django.db.models import Count
from django.utils import timezone
recent_tags = Tag.objects.filter(
    tagged_items__tagged_item_timestamp__gte=timezone.now() - timedelta(days=30)
).annotate(recent_usage=Count('tagged_items'))

# Find unused tags (orphaned tags)
unused_tags = Tag.objects.filter(tagged_items__isnull=True)

# Most active tags across all models
from django.contrib.contenttypes.models import ContentType
active_tags = Tag.objects.annotate(
    total_usage=Count('tagged_items')
).order_by('-total_usage')[:10]

Advanced Usage Patterns

Conditional Tag Operations

Perform tag operations based on conditions.

# Add tags conditionally
if article.is_published:
    article.tags.add("published")
else:
    article.tags.add("draft")

# Remove tags based on content
if "outdated" in article.content.lower():
    article.tags.remove("current")
    article.tags.add("needs-update")

Tag Hierarchies and Relationships

While django-taggit doesn't natively support hierarchical tags, you can implement patterns for related tags.

# Tag categories through naming conventions
article.tags.add("lang:python", "framework:django", "level:beginner")

# Filter by tag categories
python_articles = Article.objects.filter(tags__name__startswith="lang:python")
beginner_articles = Article.objects.filter(tags__name__startswith="level:beginner")

Performance Optimization

Best practices for efficient tag operations.

# Use select_related and prefetch_related
articles = Article.objects.prefetch_related('tags').all()

# Batch tag operations
tags_to_add = ["python", "django", "tutorial"]
article.tags.add(*tags_to_add)  # Single operation instead of multiple

# Use exists() for checking tag presence
has_python_tag = article.tags.filter(name="python").exists()

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