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 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.
Comments
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
seats_availablefield in theTrainclass and set that to 100 initially. Create aSeatinstance whenever you need to (customer purchases a seat etc.) and link it to theTraininstance with a foreign key.