0
# Model Integration
1
2
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.
3
4
## Capabilities
5
6
### TaggableManager Field
7
8
The main entry point for adding tagging functionality to Django models. Acts as a Django field that provides access to tag operations.
9
10
```python { .api }
11
class TaggableManager:
12
"""
13
Field for adding tagging functionality to Django models.
14
15
Parameters:
16
- verbose_name (str): Human-readable name for the field
17
- help_text (str): Help text shown in forms and admin
18
- through (Model): Custom through model for tag relationships
19
- blank (bool): Whether field is required in forms
20
- related_name (str): Name for reverse relation
21
- to (Model): Custom tag model to use
22
- ordering (list): Default ordering for tags
23
- manager (class): Custom manager class for tag operations
24
"""
25
def __init__(
26
self,
27
verbose_name="Tags",
28
help_text="A comma-separated list of tags.",
29
through=None,
30
blank=False,
31
related_name=None,
32
to=None,
33
ordering=None,
34
manager=None
35
):
36
"""Initialize TaggableManager with configuration options."""
37
38
def __get__(self, instance, model):
39
"""
40
Return the tag manager for the instance or model.
41
42
Parameters:
43
- instance: Model instance (None for class access)
44
- model: Model class
45
46
Returns:
47
_TaggableManager: Manager instance for tag operations
48
"""
49
50
def formfield(self, form_class=None, **kwargs):
51
"""
52
Return a form field for this manager.
53
54
Parameters:
55
- form_class: Custom form field class (defaults to TagField)
56
- **kwargs: Additional form field arguments
57
58
Returns:
59
TagField: Form field for tag input
60
"""
61
62
def save_form_data(self, instance, value):
63
"""
64
Save form data to the instance's tags.
65
66
Parameters:
67
- instance: Model instance
68
- value: Form data (list of tag names or tag string)
69
"""
70
71
def value_from_object(self, obj):
72
"""
73
Get tag values from a model instance for forms.
74
75
Parameters:
76
- obj: Model instance
77
78
Returns:
79
list: List of Tag objects
80
"""
81
```
82
83
### Basic Model Setup
84
85
Simple integration with default settings using the built-in Tag and TaggedItem models.
86
87
```python
88
from django.db import models
89
from taggit.managers import TaggableManager
90
91
class Article(models.Model):
92
title = models.CharField(max_length=200)
93
content = models.TextField()
94
tags = TaggableManager()
95
96
class Product(models.Model):
97
name = models.CharField(max_length=100)
98
price = models.DecimalField(max_digits=10, decimal_places=2)
99
tags = TaggableManager(blank=True, help_text="Optional product tags")
100
```
101
102
### Custom Through Models
103
104
Using custom through models for additional fields on tag relationships.
105
106
```python
107
from taggit.models import TaggedItemBase
108
109
class TaggedFood(TaggedItemBase):
110
content_object = models.ForeignKey('Food', on_delete=models.CASCADE)
111
added_by = models.ForeignKey('auth.User', on_delete=models.CASCADE)
112
date_added = models.DateTimeField(auto_now_add=True)
113
114
class Food(models.Model):
115
name = models.CharField(max_length=100)
116
tags = TaggableManager(through=TaggedFood)
117
```
118
119
### Custom Tag Models
120
121
Using custom tag models with additional fields.
122
123
```python
124
from taggit.models import TagBase
125
126
class CustomTag(TagBase):
127
description = models.TextField(blank=True)
128
color = models.CharField(max_length=7, default='#000000')
129
130
class Item(models.Model):
131
name = models.CharField(max_length=100)
132
tags = TaggableManager(to=CustomTag)
133
```
134
135
### UUID Support
136
137
Support for models with UUID primary keys using the UUID-specific base classes.
138
139
```python
140
import uuid
141
from django.db import models
142
from taggit.models import GenericUUIDTaggedItemBase
143
144
class UUIDTaggedItem(GenericUUIDTaggedItemBase):
145
# Automatically handles UUID object_id field
146
pass
147
148
class UUIDModel(models.Model):
149
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
150
name = models.CharField(max_length=100)
151
tags = TaggableManager(through=UUIDTaggedItem)
152
```
153
154
### Multiple TaggableManagers
155
156
Using multiple tag managers on a single model for different types of tags.
157
158
```python
159
from taggit.managers import TaggableManager
160
from taggit.models import TaggedItemBase
161
162
class TaggedArticleCategory(TaggedItemBase):
163
content_object = models.ForeignKey('Article', on_delete=models.CASCADE)
164
165
class TaggedArticleKeyword(TaggedItemBase):
166
content_object = models.ForeignKey('Article', on_delete=models.CASCADE)
167
168
class Article(models.Model):
169
title = models.CharField(max_length=200)
170
categories = TaggableManager(through=TaggedArticleCategory, related_name='category_articles')
171
keywords = TaggableManager(through=TaggedArticleKeyword, related_name='keyword_articles')
172
```
173
174
### Manager Access
175
176
Accessing tag managers at the model class level for querying and filtering.
177
178
```python { .api }
179
# Access manager for model-level operations
180
Model.tags.all() # All tags used by any instance of Model
181
Model.tags.most_common() # Most commonly used tags across all instances
182
183
# Manager methods available at model level
184
def all(): ...
185
def most_common(min_count=None, extra_filters=None): ...
186
def filter(**kwargs): ...
187
```
188
189
### Prefetching and Performance
190
191
Optimizing tag queries using Django's prefetch_related functionality.
192
193
```python
194
# Prefetch tags to avoid N+1 queries
195
articles = Article.objects.prefetch_related('tags').all()
196
197
# Custom prefetch with filtering
198
from django.db.models import Prefetch
199
articles = Article.objects.prefetch_related(
200
Prefetch('tags', queryset=Tag.objects.filter(name__startswith='tech'))
201
)
202
203
# Prefetch tagged items for reverse lookups
204
tags = Tag.objects.prefetch_related('tagged_items').all()
205
```
206
207
## Configuration Options
208
209
### Settings
210
211
Django settings that affect tagging behavior globally.
212
213
```python
214
# settings.py
215
216
# Case-insensitive tag matching
217
TAGGIT_CASE_INSENSITIVE = True
218
219
# Strip unicode when creating slugs
220
TAGGIT_STRIP_UNICODE_WHEN_SLUGIFYING = True
221
222
# Custom tag parsing function
223
TAGGIT_TAGS_FROM_STRING = 'myapp.utils.custom_parse_tags'
224
225
# Custom tag formatting function
226
TAGGIT_STRING_FROM_TAGS = 'myapp.utils.custom_format_tags'
227
```
228
229
### Field Options
230
231
Options available when defining TaggableManager fields.
232
233
```python
234
class MyModel(models.Model):
235
# Basic field
236
tags = TaggableManager()
237
238
# Optional field with custom help text
239
categories = TaggableManager(
240
blank=True,
241
help_text="Categorize this item",
242
verbose_name="Categories"
243
)
244
245
# Custom ordering
246
ordered_tags = TaggableManager(
247
ordering=['name'], # Alphabetical order
248
related_name='ordered_items'
249
)
250
```