Mazen Ahmed
Mazen Ahmed

Reputation: 57

Creating automatic objects in the Database (Django)

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

Upvotes: 0

Views: 151

Answers (2)

Daniel Hepper
Daniel Hepper

Reputation: 29967

Technically, there are multiple solutions to your problem:

  1. You can listen to the post_save signal.
  2. You can overwrite the save() method on your Train model.
  3. You can create a ModelAdmin subclass with a custom save_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.

Upvotes: 1

Ozgur Akcali
Ozgur Akcali

Reputation: 5492

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

Upvotes: 0

Related Questions