gpt4 book ai didi

mysql - Complex 加入 Peewee

转载 作者:行者123 更新时间:2023-11-29 03:01:25 25 4
gpt4 key购买 nike

问这个问题很尴尬,因为它似乎微不足道,但我找不到有效的解决方案。

我有以下功能:

def planner(departure_id, arrival_id):
departure = Stop.get(Stop.id == departure_id)
arrival = Stop.get(Stop.id == arrival_id)
buses = Bus.select().join(RideStopRelationship).join(Stop).where(Stop.id == departure)
for bus in buses:
print bus.line
for stop in bus.stops:
print stop.time, stop.stop.name

基于以下模型:

class Stop(BaseModel):
name = CharField()
#lat = FloatField()
#lng = FloatField()

class Bus(BaseModel):
line = IntegerField()
number = IntegerField()
direction = IntegerField()

class RideStopRelationship(BaseModel):
bus = ForeignKeyField(Bus, related_name = "stops")
stop = ForeignKeyField(Stop, related_name = "buses")
time = TimeField()

关键行是 Bus.select().join(RideStopRelationship).join(Stop).where(Stop.id == department)。我正在尝试让所有将在 departurearrival 停靠的公共(public)汽车。但是,上述查询返回所有停靠在 departure 的公交车。我如何获得在“出发”和“到达”都停靠的巴士?

如果我把它弄得太复杂(要么是我的模型太复杂,要么是我的查询),请随时纠正我。

编辑:有一种方法确实有效:

buses_departure = Bus.select().join(RideStopRelationship).join(Stop).where(Stop.id == departure)
buses_arrival = Bus.select().join(RideStopRelationship).join(Stop).where(Stop.id == arrival)
buses = Bus.select().where(Bus.id << buses_departure & Bus.id << buses_arrival)

但是对于应该是简单查询的内容来说它相当长...

最佳答案

你可以尝试这样的事情:

departure = Stop.get(...)
arrival = Stop.get(...)
query = (Bus
.select(Bus)
.join(RideStopRelationship)
.where(RideStopRelationship.stop << [departure, arrival])
.group_by(Bus)
.having(fn.Count(Bus.id) == 2))

无关,但需要注意的一件事是,由于 python 评估运算符的方式,您需要在 in 查询中加上括号:

buses = Bus.select().where(
(Bus.id << buses_departure) &
*Bus.id << buses_arrival))

关于mysql - Complex 加入 Peewee,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23035009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com