Stack Exchange
Django, how to get new id during save
I have this code:
class Unit(Location):
    Name = models.CharField(max_length=100, unique=True)
    Hull = models.CharField(max_length=25, unique=True)
    Type = models.CharField(max_length=5, CHOICES=UNIT_TYPE_CHOICE)
    Precomm = models.BooleanField(default=True)
    Email = models.CharField(max_length=250, verbose_name="Email")
    Phone = models.CharField(max_length=20, verbose_name="Primary Phone")

    def __self__(self):
        return self.Name + ' (' + self.Hull + ')'

    def save(self, *args, **kwargs):
        if not self.pk:
            co = Position(Name='Commanding Officer', Description='Position in command of chapter.', Unit=self.pk)
            co.save()
            xo = Position(Name='Executive Officer', Description='Second in Command of Chapter', Unit=self.pk)
            xo.save()
            cob = Position(Name='Chief of the Boat', Description='Senior Enlisted Adviser in charge of cadet affairs', Unit=self.pk)
            cob.save()
        super(Unit, self).save(args, kwargs)


class Position(models.Model):
    Name = models.CharField(max_length=100)
    Description = models.TextField()
    Unit = models.ForeignKey(Unit)

The idea is to auto-create three Positions when a Unit is saved.  The positions are set in the save process.  My concern is that self.pk is not created at the point of the save definition.  How do I get the id so I can create the three records?
Thanks

The id will be populated after calling super, so you can use a flag:
created = self.pk is None
super(Unit, self).save(args, kwargs)
if created:
    ...


You should use signals instead of overriding save, especially if you want to do something like this. Docs are here
from django.db.models.signals import post_save
from django.dispatch import receiver

class Unit(models.Model):
    # ... fields here


@receiver(post_save, sender=Unit)
def create_related(sender, instance, created, **kwargs):
    if created:
        co = Position(Name='Commanding Officer', Description='Position in command of chapter.', Unit=instance.pk)
        co.save()
        xo = Position(Name='Executive Officer', Description='Second in Command of Chapter', Unit=instance.pk)
        xo.save()
        cob = Position(Name='Chief of the Boat', Description='Senior Enlisted Adviser in charge of cadet affairs', Unit=instance.pk)
        cob.save()

