如何使用 Django ORM 执行这个复杂的 SQL 查询? (带连接的子查询)
我已经习惯了编写自己的 SQL 查询,并且正在尝试适应当今似乎如此流行的整个 ORM 事物。
这是查询:
SELECT * FROM routes WHERE route_id IN (
SELECT DISTINCT t.route_id FROM stop_times AS st
LEFT JOIN trips AS t ON st.trip_id=t.trip_id
WHERE stop_id = %s
)
其中 %s 是整数。
我正在使用 Django 的默认 ORM。最Pythonic的方法是什么?
一些背景信息:我使用的数据库来自 GTFS(Google Transit feed 规范)。该查询应该获取经过特定stop
的每条route
的列表,但是链接这些的信息位于trips
表中。
这个查询对我来说效果很好,所以我问的唯一原因是学习。
谢谢!
I'm used to writing my own SQL queries and I'm trying to get used to the whole ORM thing that seems to be so popular nowadays.
Here's the query:
SELECT * FROM routes WHERE route_id IN (
SELECT DISTINCT t.route_id FROM stop_times AS st
LEFT JOIN trips AS t ON st.trip_id=t.trip_id
WHERE stop_id = %s
)
where %s is an integer.
I'm using Django's default ORM. What's the most pythonic way to do this?
Some background info: The DB I'm using is from a GTFS (Google Transit feed specification). This query is supposed to get a list of every route
that goes through a particular stop
, however the info linking these is in the trips
table.
This query works just fine for me, so the only reason I'm asking is to learn.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您拥有用于相关
模型
的内容,那么找出执行此操作的适当方法可能会更容易一些。根据您提到的工作规范,我假设如下所示:
如果是这种情况...您应该能够执行类似
获取经过给定的所有
Route
对象的操作Stop
的主键id
等于my_stop_id
,我假设根据您的帖子是一个整数。如果语法有点不对,我深表歉意,因为我不需要使用显式的额外表来建立多对多关系。如果您必须(或选择)对任何外键或多对多字段使用
lated_name
参数,则可能还需要进行一些调整。It'd probably be a bit easier to figure out the appropriate way to do this if you had what you were using for the relevant
Models
.I'm assuming something like the following, based on the specification you mentioned working from:
If that's the case... you should be able to do something like
to get all
Route
objects that go through a givenStop
with a primary keyid
equal tomy_stop_id
, which I'm assuming is an integer as per your post.I apologize if the syntax is a bit off, as I haven't needed to do many-to-many relationships using an explicit extra table. Some adjustment may also be needed if you have to (or choose to) use the
related_name
parameter for any the foreign keys or the many-to-many-field.如果我错了,请纠正我,但我认为你不能以正常的方式使用 Django ORM 做到这一点。
没有子查询支持,并且使用普通连接,如果不同的可以帮助您,则取决于您的数据库。如果您使用的是 Postgres,则可以使用此补丁来完成此操作: http://code.djangoproject.com/ticket /6422
查询将如下所示:
Correct me if I'm wrong, but I don't think you can do that with Django ORM in a normal way.
There is no subquery support and with a normal join it would depend on your database if a distinct could help you. If you are using Postgres than you could do it with this patch: http://code.djangoproject.com/ticket/6422
The query would be something like this: