David Lopez
David Lopez

Reputation: 83

Add a model with a foreign key

I'm using Django and I have two models:

class Source(models.Model):
  def __str__(self):
    return "Test"



class SecurityGroup(models.Model)
  name = models.CharField(max_length=20)
  source = models.ForeignKey(Source)

I want that when I add a new SecurityGroup, automatically will append a new Source with his ID, and this ID will the source camp in the SecurityGroup.

I've been looking and I found override the method save(), but I don't know how to do..

Thanks!!

Upvotes: 2

Views: 53

Answers (2)

ilse2005
ilse2005

Reputation: 11429

As you mentioned you can override the save method of SecurityGroup and create a new Source object there:

class SecurityGroup(models.Model)
    name = models.CharField(max_length=20)
    source = models.ForeignKey(Source)

    def save(self, *args, **kwargs):
        if self.source is None:
            self.source = Source.objects.create()
        super(SecurityGroup, self).save(*args, **kwargs)

Upvotes: 2

Tomasz Jakub Rup
Tomasz Jakub Rup

Reputation: 10680

Read about signals.

post_save version:

from django.db.models.signals import post_save
from django.dispatch.dispatcher import receiver

@receiver(post_save, sender=SecurityGroup)
def add_source(sender, instance, created, **kwargs):
    if created:
        source = Source()
        source.save()
        instance.source = source
        instance.save()

pre_save version:

from django.db.models.signals import pre_save
from django.dispatch.dispatcher import receiver

@receiver(pre_save, sender=SecurityGroup)
def add_source(sender, instance, **kwargs):
    if instance.source is None:
        source = Source()
        source.save()
        instance.source = source

Upvotes: 2

Related Questions