构造一个排序内连接的 django 查询集
我正在尝试跟踪基于 django 的网站中的页面浏览量。我有以下模型
class PageView:
date = DateTimeField( auto_now=True )
user = ForeignKey( User )
page = ForeignKey( Page )
来跟踪页面的每次查看。我想构建一个查询集,返回用户最近查看的页面,并按查看每个页面的日期排序。例如,如果我有以下页面浏览量:
date | user_id | page_id |
2011-02-20 | 5 | 2 |
2011-02-19 | 5 | 1 |
2011-02-24 | 5 | 1 |
2011-02-23 | 5 | 2 |
我希望查询集
date | page_id | title | and everything associated with the page
2011-02-24 | 1 | "page 1" |
2011-02-23 | 2 | "page 2" |
按此顺序返回!
在 SQL 中,我可以通过
SELECT p.*, v.date FROM page p,
(SELECT page_id, MAX(date) date FROM pageview
WHERE user_id=5 GROUP BY page_id) AS v where p.id=v.page_id
ORDER BY v.date;
但是如何使用 django queryset API 构造它?
我将非常感谢任何帮助!
I am trying to track page views in a django-based website. I have the following model
class PageView:
date = DateTimeField( auto_now=True )
user = ForeignKey( User )
page = ForeignKey( Page )
to track each viewing of the page. I want to construct a queryset that returns a user's recently viewed Pages ordered by the date each page is viewed. For example, if I have the following page views:
date | user_id | page_id |
2011-02-20 | 5 | 2 |
2011-02-19 | 5 | 1 |
2011-02-24 | 5 | 1 |
2011-02-23 | 5 | 2 |
I want to the queryset to return
date | page_id | title | and everything associated with the page
2011-02-24 | 1 | "page 1" |
2011-02-23 | 2 | "page 2" |
IN THAT ORDER!
In SQL, I can do it by
SELECT p.*, v.date FROM page p,
(SELECT page_id, MAX(date) date FROM pageview
WHERE user_id=5 GROUP BY page_id) AS v where p.id=v.page_id
ORDER BY v.date;
But how can I construct it using django queryset API?
I will greatly appreciate any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有关 SQL 连接的更多参考,请参阅文档
For further reference in SQL joins see Documentation