Ryan Currah
Ryan Currah

Reputation: 1105

How do I run a method when a model gets created?

Currently I am using signals to fireoff the creation of my IPs when a new Subnet is created.

But some people in #django said the better way was to create a custom save() or let form handle it if there is ForeingKey.

Is there a more appropriate solution than using signals? If so can someone show me a code example?

My Subnet model (models.py):

class Subnet(models.Model):
    network_address = models.IPAddressField()
    subnet_prefix = models.ForeignKey(SubnetPrefix)

My IP Address model (models.py):

class IPAddress(models.Model):
    subnet = models.ForeignKey(Subnet)
    ip_address = models.IPAddressField()
    hostname = models.CharField(max_length=255, null=True, blank=True)

My signal (models.py):

def subnet_post_save(sender, instance, created, *args, **kwargs):
        # If this is a new object create ip_addresses in IPAddress table
        if created:
            create_ip_addresses(instance)

Upvotes: 2

Views: 69

Answers (1)

niekas
niekas

Reputation: 9117

You have to override save method:

class Subnet(models.Model):
    network_address = models.IPAddressField()
    subnet_prefix = models.ForeignKey(SubnetPrefix)

    def save(self, *args, **kwargs):
        created = not self.pk
        super(Subnet, self).save(*args, **kwargs)
        if created:
            create_ip_addresses(self)

Upvotes: 3

Related Questions