i am working on train booking system project and i want to access the seat number and location so i made a seats class that will help. the issue is that i want when the admin adds a new train from the admin panel the seats class automatically adds 100 seat into the DB because i don't think it makes any sense that the admin will add the 100 seat manually
- 
                    2https://stackoverflow.com/questions/53535389/django-creating-model-instances-newbie – Ivan Starostin Nov 30 '18 at 09:47
- 
                    Without knowing your full requirements, perhaps you'd be best to have a `seats_available` field in the `Train` class and set that to 100 initially. Create a `Seat` instance whenever you need to (customer purchases a seat etc.) and link it to the `Train` instance with a foreign key. – Laurence Quinn Nov 30 '18 at 09:50
2 Answers
Technically, there are multiple solutions to your problem:
- You can listen to the post_savesignal.
- You can overwrite the save()method on yourTrainmodel.
- You can create a ModelAdminsubclass with a customsave_model()method.
If you want to make sure that it is impossible to create a Train without creating the associated Seat instances, overwrite save(). Using a signal gives you a slightly less tight coupling, but I don't think it will give you any benefit here.
When overwriting save(), you can check if self.pk is None to see if a model is created or updated:
# models.py
class Train(models.Model):
    ...
    def save(self, *args, *kwargs):
        created = self.pk is None
        super().save(*args, **kwargs)
        if created:
            self.create_seats()
If you want to only create Seats when a Train is created through the admin, create a custom ModelAdmin:
class TrainAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)
        if not change:
            obj.create_seats()
Both examples assume your Train class has a create_seats() method.
 
    
    - 28,981
- 10
- 72
- 75
You can override save method of your model or use a post_save signal on Train model.
First approach, overriding model save method:
class Train(models.Model):
    .
    .
    .
    def save(self, *args, **kwargs):
        is_new = not self.pk
        # Call save method of super
        super(Train, self).save(*args, **kwargs)
        # Add your seats here
Second approach, using a signal, write this to your models.py file:
@receiver(models.signals.post_save, sender=Train)
def post_train_save(sender, instance, created, *args, **kwargs):
    if created:
        # Add your seats here
 
    
    - 5,264
- 2
- 31
- 49
