I am trying to make my first website with django. Basically I'm making a website to check the bus schedule in my rural area. I think that the best thing is to make two models, one where all the bus stations are defined and the other where the route is established, for each route two stations are needed (origin and destination). I was wondering what was the best way to relate the two models.
class BusStations(models.Model):
bus_stations = models.CharField(max_length=80)
bus_stations_identifier = models.IntegerField()
def __str__(self):
return self.bus_stations
class Routes(models.Model):
origin_station = models.ManyToManyField(
BusStations, related_name='origin_station')
destination_station = models.ManyToManyField(
BusStations, related_name='destination_station')
data = models.JSONField()
slug = models.SlugField(unique=True, null=True)
def __str__(self):
return f'{self.origin_station} - {self.estacion_destino}'
For now I was doing it with ManytoMany relationships, but this is giving me problems. For example, I am not able to return the origin and destination stations as str in the route model. I would also like it to be the slug.
CodePudding user response:
The origin_station
and destionation_station
likely each point to a single station, so then you use a ForeignKey
[Django-doc], not a ManyToManyField
:
class BusStation(models.Model):
bus_station = models.CharField(max_length=80)
bus_station_identifier = models.IntegerField()
def __str__(self):
return self.bus_station
class Route(models.Model):
origin_station = models.ForeignKey(
BusStation, related_name='starting_routes'
)
destination_station = models.ForeignKey(
BusStation, related_name='ending_routes'
)
data = models.JSONField()
slug = models.SlugField(unique=True, null=True)
def __str__(self):
return f'{self.origin_station} - {self.destionation_station}'