[Answer]-Delete related models in django through a ManyToManyField

1👍

✅

You could do it board .delete(). Something like this:

def delete(*args, **kwargs):
    self.card_set.annotate(board_count=Count('boards')).filter(board_count=1).delete()
    super(Board, self).delete(*args, **kwargs)

This will select all of the boards related cards, and then filter on out the cards that are associated with more than one board. (You already know one of the boards is the current board) And then delete them.

It is also important to remember that this will only be called when you call .delete() on a single board. Not on a queryset.

EDIT: since .delete() is not called when calling .delete() on a query set, I think the pre_delete signal would be a better choice:

@receiver(pre_delete, sender=Board)
def delete_associated_cards(sender, instance, using, **kwargs):
    instance.card_set.annotate(board_count=Count('boards')).filter(board_count=1).delete()
👤jproffitt

Leave a comment