Django嵌套查询PostgreSQL

时间:2017-06-26 19:51:12

标签: django postgresql python-3.x django-queryset django-orm

class Route(app_core_base_model.AbstractDefaultModel):
code = models.PositiveIntegerField(
    verbose_name=_('code'),
    default=0,
    editable=True)
slug = models.SlugField(
    verbose_name=_('slug'),
    unique=True,
    max_length=255,
    blank=True,
    null=True,
    editable=True,
    db_index=True)

class Route(app_core_base_model.AbstractDefaultModel):
code = models.PositiveIntegerField(
    verbose_name=_('code'),
    default=0,
    editable=True)
slug = models.SlugField(
    verbose_name=_('slug'),
    unique=True,
    max_length=255,
    blank=True,
    null=True,
    editable=True,
    db_index=True)

class StopPoint(app_core_base_model.AbstractDefaultModel):
route = models.ForeignKey(
    Route,
    verbose_name=_('route'))
station = models.ForeignKey(
    app_core_models.Station,
    verbose_name=_('station'))
arrival_time = models.TimeField(
    verbose_name=_('arrival time'),
    blank=True,
    null=True,
    editable=True)
departure_time = models.TimeField(
    verbose_name=_('departure time'),
    blank=True,
    null=True,
    editable=True)

class Station(app_core_base_model.AbstractDefaultModel):
name = models.CharField(
    verbose_name=_('name station'),
    max_length=255,
    blank=True,
    null=True,
    editable=True)
slug = models.SlugField(
    verbose_name=_('slug'),
    unique=True,
    max_length=255,
    blank=True,
    null=True,
    editable=True,
    db_index=True)

我有3个型号 我无法提出能够选择所有通过抵达点和出发地点的航班的请求。

如何找到所有经过的路线以及到达目的地的出发点?

1 个答案:

答案 0 :(得分:0)

这应该可以解决问题。您需要使用反向FK关系。文档:https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ForeignKey.related_name

station1 = Station.objects.get(...)
station2 = Station.objects.get(...)
routes = Route.objects.filter(
    stoppoint_set__station=station1, 
    stoppoint_set__station=station2).distinct()