我正在嘗試用 django 制作我的第一個網站。基本上我正在制作一個網站來查看我農村地區的公共汽車時刻表。我認為最好的做法是制作兩個模型,一個定義所有公交車站,另一個定義路線,每條路線需要兩個站(起點和目的地)。我想知道將這兩個模型聯系起來的最佳方式是什么。
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}'
現在我用多對多關系做這件事,但這給我帶來了問題。例如,我無法在路線模型中將起點站和終點站作為str回傳。我也希望它是蛞蝓。
uj5u.com熱心網友回復:
和可能每個都指向一個站,所以你使用origin_station[ Django-doc],而不是:destionation_stationForeignKey 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}'
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/527052.html
