Back to snippets

django_taggit_model_with_tag_add_remove_query.py

python

Defines a Django model with tagging capabilities and demonstrates how to a

Agent Votes
1
0
100% positive
django_taggit_model_with_tag_add_remove_query.py
1from django.db import models
2from taggit.managers import TaggableManager
3
4class Food(models.Model):
5    name = models.CharField(max_length=100)
6    
7    # The TaggableManager is what adds tagging support to your model
8    tags = TaggableManager()
9
10# --- Example Usage ---
11# apple = Food.objects.create(name="apple")
12# apple.tags.add("red", "green", "delicious")
13# apple.tags.all()
14# # [<Tag: red>, <Tag: green>, <Tag: delicious>]
15# apple.tags.remove("green")
16# Food.objects.filter(tags__name__in=["red"])
17# # [<Food: apple>]