[Answer]-Create a Django model with referencing Models in Manager class

1👍

How would I go about creating a “Company” with a default “Showroom?

Override the save method of model Company or register a post save signal on model Company.

Can I use the unsaved company to create my showroom?

No.

Updated:

class Company(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

    def save(*args, **kwargs):
        super(Company, self).save(*args, **kwargs)
        self.showroom__set.create(name=self.name)

Updated by Berdus:

class Company(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

    def save(self, *args, **kwargs):
    is_first_save = self.pk is None
    super(Company, self).save(*args, **kwargs)
    if is_first_save:
        self.showroom_set.create(name=self.name)

Note the self argument in save and the single underscore on showroom_set.

0👍

This is the way I think of it.

setting.py

DEFAULT_SHOWROOM_NAME = 'blah'

models.py

class Company(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

    def save(*args, **kwargs):
        super(Company, self).save(*args, **kwargs)
        if not self.showroom__set.all():
             self.showroom__set.create(name=DEFAULT_SHOWROOM_NAME)
👤maazza

Leave a comment