Last Updated: February 25, 2016
·
804
· dizpers

Filter objects based on count of related objects and delete them! :)

For example, we have two models:

class Book(models.Model):
    title = models.CharField(max_length = 255, db_index = True)

class Thumb(models.Model):
    book = models.ForeignKey(Book)

And we want to delete all books, wich have 0 thumbs or 5 thumbs or less than or equal 5 thumbs, etc...

First, we should get list of this objects.

Get books with 0 thumbs:

bad =  Book.objects.annotate(nt=Count('thumb')).filter(nt__e=0)

Get books with 5 thumbs:

bad =  Book.objects.annotate(nt=Count('thumb')).filter(nt__e=5)

Get books with less than or equal 5 thumbs:

bad =  Book.objects.annotate(nt=Count('thumb')).filter(nt__lte=5)

Get books with greater than or equal 5 thumbs:

bad =  Book.objects.annotate(nt=Count('thumb')).filter(nt__gte=5)

Get books with less than 5 thumbs:

bad =  Book.objects.annotate(nt=Count('thumb')).filter(nt__lt=5)

Get books with greater than 5 thumbs:

bad =  Book.objects.annotate(nt=Count('thumb')).filter(nt__gt=5)

Deleting this objects is quite simple:

for item in bad:
    item.delete()