I have two models - Photo and Tag - which are connected via a ManyToManyField.
class Photo(models.Model):
tags = models.ManyToManyField(Tag)
class Tag(m
We've had to further improve performance of this task, so I modified okm's solution a bit:
all_tag_pks = Tag.objects.values_list('pk', flat=True)
used_tag_pks = Photo.tags.through.objects.values_list('tag', flat=True)
Tag.objects.filter(pk__in=list(set(all_tag_pks) - set(used_tag_pks))).delete()
By that, the query to the database gets a lot smaller and faster.