Django: get all unflagged comments for a Model

I recently had to migrate django.contrib.comments from a legacy app to a newer app, also in Django. I only wanted to move relevant comments that were unflagged (no need to duplicate spam!)

Here's how I did it (manage.py shell usage):

1
2
3
4
5
6
7
8
from django.contrib.comments.models import Comment
from django.db.models import Count
from legacy.models import LegacyArticle

las = LegacyArticle.objects.all_published()
for la in las:
    comments = Comment.objects.for_model(LegacyArticle).annotate(flagcount=Count('flags')).filter(object_pk=la.pk, flagcount=0)
    # handler code...