Home > other >  Django Models Many-to-Many remove an object
Django Models Many-to-Many remove an object

Time:09-28

Wonder if you could help me, I have models setup as follows:

class Device(models.Model):
    hostname = models.CharField(unique=True, max_length=255)
    mgmt_ip = models.GenericIPAddressField(
        blank=True, null=True, unique=True, max_length=12)
    console_ip = models.GenericIPAddressField(
        blank=True, null=True, unique=False, max_length=12
    )

class ConfigurationFile(models.Model):
    name = models.CharField(blank=True, max_length=255)
    friendly_name = models.CharField(blank=True, max_length=255)
    file = models.FileField(
        upload_to='configuration/config_files/cisco/',
        validators=[FileExtensionValidator(allowed_extensions=['cfg'])]
    )

class ConfigurationFileApplied(models.Model):
    file_object = models.ForeignKey(
        ConfigurationFile, unique=True, null=True, on_delete=models.CASCADE)
    applied_to = models.ManyToManyField(Device)

My "ConfigurationFileApplied" is associated with "ConfigurationFile" and "ConfigurationFileApplied" can be associated with multiple devices. I'm looking for a way of removing "Device" from "ConfigurationFileApplied" when config (abstract) is removed. But I can't figure out how? :-/

CodePudding user response:

when config (abstract) is removed

I'm not sure if I get that right but do you mean if you remove the file_object from ConfigurationFileApplied? If so you can create a post_save() method

from django.db.models.signals import post_save
from django.dispatch import receiver
# more imports

# your model classes here

@receiver(post_save, sender=ConfigurationFileApplied, dispatch_uid="update_devices")
def update_config(sender, instance, **kwargs):
    if not instance.file_object and instance.applied_to.all().count() > 0:
        instance.applied_to.clear()

Edit (after comment #1)

Simply remove a device from applied_to?

# assuming you know exactly which device pk to remove from which config
device = Device.objects.get(pk=device_pk)
conf = ConfigurationFileApplied.objects.get(pk=conf_pk)

# remove this device from the conf
conf.applied_to.remove(device)

# remove all devices from the conf
conf.applied_to.clear()

# there is no need for to .save()
  • Related