如何在Django中将此SQL查询“翻译”为queryset

时间:2019-05-03 01:02:05

标签: django django-models orm django-queryset

所以我有了这些Django模型(通过简化的方式简化了代码):

    class Travel(models.Model):
      #there are many other fields
      origin_city = CharField()
      end_city = CharField()

    class Segment(models.Model):
      start_time = DateTimeField()
      origin = CharField()
      end = CharField()
      travel = ForeignKey(Travel)
      price = IntegerField()

因此,旅行有一组细分,例如,如果旅行是A-> B-> C-> D-> E,则这些细分是(A,B),(B,C),(C ,D)和(D,E)。我想给出一个起点和终点,即经过给定起点然后经过给定终点的行程。例如,如果起点和终点为(B,D),则示例行进是有效的,因为它在某个点经过B,然后在以后经过D,但对(D,B)无效。

我知道在SQL中,可以这样进行操作(假设旅行商店的id和segment具有外键限制):

    SELECT t.*
    FROM travel as t, segment as s1,segment as s2
    WHERE t.id = s1.travel_id AND t.id = s2.travel_id
    AND s1.origin = (user given origin)
    AND s2.end = (user given end)
    AND s1.start_time < s2.start_time

1 个答案:

答案 0 :(得分:0)

以下查询将带您到达,并以user_originuser_end作为用户提供的条件:

travels = (Travel.objects
    .filter(segment__origin=user_origin)
    .annotate(origin_time=F('segment__start_time'))
    .filter(segment__end=user_end, segment__start_time__gt=F('origin_time'))
)

您获取对第一个start_time联接的Segment的引用,并在第二个filter()中引用它,从而创建了对Segment的第二个联接。 / p>