Reputation: 417
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
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