Django Model field : Ordered List of Foreign Keys

☆樱花仙子☆ 提交于 2019-12-08 17:24:44

问题


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

回答1:


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()


来源:https://stackoverflow.com/questions/31601597/django-model-field-ordered-list-of-foreign-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!