0

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

2
  • 2
    stackoverflow.com/questions/53535389/… Commented Nov 30, 2018 at 9: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. Commented Nov 30, 2018 at 9:50

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.