0

Consider a train ticket booking app. There are many cities, stations and trains.

Each city has one/more stations. It is obvious that a station can not be in more than one city. Each station receive one/more train(s). Every train visits one or more station and finally stops at a fixed (common) destination.

Now I want to make a form where the user is able to select his city, stations in the same city and then the train (which that station of the city receives) and finally book the train.
This is what I have done till now.

class City(models.Model):
    name = models.CharField(max_length=50, help_text="Your city name")

class Train(models.Model):
    number = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=50, help_text="Train")
    city = models.ForeignKey(City)



class Station(models.Model):
   city = models.ForeignKey(City)
   name = models.CharField(max_length=50, help_text="All available stations in your city")

class BookedTicket(models.Model):
   city = models.ForeignKey(City)
   station = models.ForeignKey(Station)
   train = models.ForeignKey(Train)

Please suggest on how to establish relationships properly because I am not able to display correct stations for a chosen city and similarly, train for a chosen city and station.

1 Answers1

0

You could use the _set to find the stations in a city

my_city = City.objects.get(name="my hometown") 
stations_in_city = my_city.station_set.all()

Also see the documentation here and here for some examples.

BartDur
  • 1,086
  • 1
  • 12
  • 21
  • Thanks. I did understand it a bit. What I want to ask is, suppose I make a form in forms.py named BookTicket form which contains the fields city, station and train. Now if a user selects a city from the drop down, the the drop down menu corresponding to station should automatically be updated so that the (city, station) is a valid data. Similarly, (city, station, train) should also be a valid data. Do you have any suggestion to do the same? – Vishal Kumar Mishra Apr 08 '17 at 16:16
  • Thanks for accepting the answer. In the drop down menus, you can define the queryset that should be used as the choices. However, you want to dynamically update this depending on the choice of another field. As far as I know you have to use some client side code for this. E.g. by sending the choice of city using e.g. Jquery and Ajax to the server (when user selects a city), get the queryset (e.g. the stations in the city) from the database and return a jsonresponse of valid stations that you then use to update the choices in the station field. Not so easy....good luck! – BartDur Apr 11 '17 at 09:25
  • check this question for example: [Django model choice field - depend on other field's choice](http://stackoverflow.com/questions/24431827/django-model-choice-field-depend-on-other-fields-choice) – BartDur Apr 11 '17 at 09:28