Skip to content

Commit

Permalink
Merge pull request #917 from guel-codes/admin-orphaned-tags
Browse files Browse the repository at this point in the history
Add an admin action to remove orphaned tags
  • Loading branch information
rtpg authored Oct 10, 2024
2 parents 9e84f93 + 2181a42 commit f4f82af
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 2 deletions.
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

0 comments on commit f4f82af

Please sign in to comment.