Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an admin action to remove orphaned tags #917

Merged
merged 4 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ Changelog
(Unreleased)
~~~~~~~~~~~~

* Add an admin command to remove orphaned tags

6.1.0 (2024-09-29)
~~~~~~~~~~~~~~~~~~

Expand Down
13 changes: 12 additions & 1 deletion taggit/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class TagAdmin(admin.ModelAdmin):
ordering = ["name", "slug"]
search_fields = ["name"]
prepopulated_fields = {"slug": ["name"]}
actions = ["render_tag_form"]
actions = ["render_tag_form", "remove_orphaned_tags_action"]

def get_urls(self):
urls = super().get_urls()
Expand Down Expand Up @@ -84,3 +84,14 @@ def merge_tags_view(self, request):
"selected_tag_ids": selected_tag_ids,
}
return render(request, "admin/taggit/merge_tags_form.html", context)

@admin.action(description="Remove orphaned tags")
def remove_orphaned_tags_action(self, request, queryset):
try:
orphaned_tags = queryset.objects.orphaned()
count, _ = orphaned_tags.delete()
self.message_user(
request, f"Successfully removed {count} orphaned tags.", level="success"
)
except Exception as e:
self.message_user(request, f"An error occurred: {e}", level="error")
2 changes: 1 addition & 1 deletion taggit/management/commands/remove_orphaned_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ class Command(BaseCommand):
help = "Remove orphaned tags"

def handle(self, *args, **options):
orphaned_tags = Tag.objects.filter(taggit_taggeditem_items=None)
orphaned_tags = Tag.objects.orphaned()
count = orphaned_tags.delete()
self.stdout.write(f"Successfully removed {count} orphaned tags")
9 changes: 9 additions & 0 deletions taggit/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,16 @@ def slugify(self, tag, i=None):
return slug


class TagQuerySet(models.QuerySet):

def orphaned(self):
return self.filter(taggit_taggeditem_items=None)


class Tag(TagBase):

objects = NaturalKeyManager.from_queryset(TagQuerySet)()

class Meta:
verbose_name = _("tag")
verbose_name_plural = _("tags")
Expand Down
Loading