1👍
✅
This answer assumes the buses can have different seat layouts, which means you’ll need to define the seating pattern for each bus type.
The most basic way would be to define them as constants, as 2-dimensional lists/arrays, entering 1 for a seat and 0 for no seat:
#seating_patterns.py
BUS_1 = [
[1, 1, 0, 1, 1],
[1, 1, 0, 1, 1],
[1, 1, 0, 1, 1],
[1, 1, 0, 1, 1],
[1, 1, 0, 0, 0],
[1, 1, 0, 1, 1],
[1, 1, 0, 1, 1],
[1, 1, 0, 1, 1],
[1, 1, 1, 1, 1],
]
BUS_2 = [etc]
SEATING_ARRAYS = {'BUS_1': BUS_1, 'BUS_2': BUS_2}
To make this more maintainable you could create a SeatingPattern model, for instance with an ArrayField if that is an option for you.
Otherwise import the seating arrays into your models file:
# models.py
from .seating_patterns import SEATING_ARRAYS
and add a seating_pattern field to your bus model, with a choices tuple for the buses:
class Bus(models.Model):
…
SEATING_PATTERNS = (
('BUS_1', 'BUS_1'),
('BUS_2', 'BUS_2'),
)
…
seating_pattern = models.CharField(choices=SEATING_PATTERNS, max_length=50)
And create the correct format output (1_1, 1_2, etc) like this in your post_save signal:
if created:
seating_pattern = SEATING_ARRAYS[instance.seating_pattern]
for row,seats in enumerate(seating_pattern):
for pos,seat in enumerate(seats):
if seat:
Seat.objects.create(
bus=instance,
position="{}_{}".format(str(row+1), str(pos+1))
)
1👍
Assuming that the bus layout is always the same:
@receiver(post_save, sender=Bus)
def create_seats(sender, instance, created, **kwargs):
if created:
for place_num in range(1, int(instance.capacity)+1):
row = (place_num // 5) + 1
col = (place_num % 5) + 1
if col != 3 and row*col not in [24, 25]:
instance.seat_set.create(position='%i_%i' % (row, col))
- [Answered ]-Including urls of one app into urls file of another app in django
- [Answered ]-Passing kwargs into get_or_create method in Django
- [Answered ]-Django1.8 and Mongoengine NameError: name 'IntegerField' is not defined
Source:stackexchange.com