smithy
smithy

Reputation: 417

How do I delete an object if not referenced by another object

I have two models similar to this:

class ContactDetails(Model):
  name = models.CharField()
  dept = models.CharField()

class Server(Model):
  ip = models.GenericIPAddressField()                           
  hostname = models.CharField()
  contact = models.ForeignKey(ContactDetails)

A ContactDetails object may be referenced by many Server objects.

When I delete a Server record, I'd like to also delete the associated ContactDetails record.

But only if there are no other Server records referencing that ContactDetails record. What's the best practice way of doing this in Django?

Upvotes: 1

Views: 692

Answers (1)

professorDante
professorDante

Reputation: 2405

Probably using either pre_delete or post_delete signals.

from django.db import models
from django.dispatch import receiver

@receiver(models.signals.post_delete, sender=Server)
def delete_contact(sender, instance, **kwargs):
    if not Server.objects.filter(contact=instance.contact):
        instance.contact.delete()

The instance is the Server instance that has already been removed from the db.

Upvotes: 3

Related Questions