[Django]-Iterating through all foreign key related children of an abstract django model

4👍

You could use the subclass() method of the ClusteringRecord. For example:

@classmethod
def related_set(cls, wip):
  classes = cls.__subclasses__()
  return sum([c.objects.filter(wip=wip).all() for c in classes], [])

And use this to iterate over your objects.

For the pre_delete signal, you need to have a signals.py file in your application, that could look like that:

from django.db.models.signals import pre_delete, post_delete
from django.dispatch import receiver

from myapp.models import ClusteringWIP

@receiver(pre_delete, sender=ClusteringWIP)
def on_instance_delete(sender, instance, **kwargs):
    instance.on_pre_delete()

With the ClusteringWIP::on_pre_delete method like so:

def on_pre_delete(self):
  for record in ClusteringRecord.related_set(self):
    record.cluster_comment = None
    record.save()

Leave a comment