Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Model field : Ordered List of Foreign Keys

I have a Route model which should store an ordered list of stops along that route. How should I go about modeling this relation?

class Stop(models.Model):
    name = ..
    latitude = ..
    longitude = ..

class Route(models.Model):
    stops_list = # Ordered list of stops on the route
like image 401
anon Avatar asked Jul 24 '15 03:07

anon


1 Answers

Since there are many Stops along a Route, and stops could belong to multiple routes, I would use a ManyToMany to store this relationship. You may specify a through model to store data about the relationship, such as what time the route is expected to arrive at this stop. There are many options to add order information. One naive way would be to have an Integer order field as below, or you could store order implicity via arrival_time. If these routes do not change often, IntegerField is not a terrible implementation. However, if they do change often then you would need to update the fields.... not ideal.

class Stop(models.Model):
    name = ..
    latitude = ..
    longitude = ..

class Route(models.Model):
    stops_list = models.ManytoManyField(Stop, through='StopInfo') # Ordered list of stops on the route

class StopInfo(models.Model):
    """ Model for storing data about the Stop/Route relationship """
    stop = models.ForeignKey(Stop)
    route = models.ForeignKey(Route)
    arrival_time = models.DateTimeField(auto_now_add=True)
    order = models.PositiveIntegerField()
like image 94
Mark Galloway Avatar answered Oct 12 '22 15:10

Mark Galloway