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)
- [Answer]-Add table cell using JQuery
- [Answer]-Load django form template with Jquery
- [Answer]-Is it possible to call different function of class based views through different actions in template
- [Answer]-Django change foreignkey Field
- [Answer]-Storing the customized django auth_user model
Source:stackexchange.com