Django模型字段:有序的外键列表 [英] Django Model field : Ordered List of Foreign Keys

查看:153
本文介绍了Django模型字段:有序的外键列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个路线模型,该模型应该存储沿该路线的有序列表。我应该怎么去建模这个关系?

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


推荐答案

由于路线上有很多停靠点,而停靠点可能属于多条路线我将使用 ManyToMany 存储此关系。您可以指定一个通过模型来存储有关关系的数据,例如在什么时候路线预计到达这个站。有很多选项来添加订单信息。一个天真的方法是具有如下的整数订单字段,或者您可以通过arrival_time存储订单隐含。如果这些路由不经常变化,IntegerField不是一个可怕的实现。然而,如果他们经常改变,那么你需要更新字段....不理想。

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

这篇关于Django模型字段:有序的外键列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆