Django 组/聚合

发布于 2024-08-22 12:59:56 字数 704 浏览 10 评论 0原文

我有以下包含示例数据的结构:(

id   season_id    title 
1    1            Intro
2    1            Second part
3    1            Third part
4    4            Other intro
5    4            Other second part

不要问为什么),其中 season_id 始终指向季节第一集的 id...

我想要的是,得到以下内容:

1    1            Intro
4    4            Other intro

从技术上讲,季节第一集 - 全部season_eid 最低的条目

,我正在使用以下查询来获取它们的 id:

Movie.objects.filter(category_type = 2).values('season_eid').annotate(models.Min('season_eid'))

并且有了 id,我可以使用 django orm __in 构造获取对象的所有数据。

我可以仅使用一个查询进行分组/注释并获取所有字段/值吗?值+注释只给了我字典列表,但我希望获得适当的对象(季节节假日的最低值/分钟)以及其余字段。

I have following structure with example data:

id   season_id    title 
1    1            Intro
2    1            Second part
3    1            Third part
4    4            Other intro
5    4            Other second part

(don't ask why), where season_id is always point to id of first episode of season...

What i want, to get following:

1    1            Intro
4    4            Other intro

which are first episoded for season, technically speaking - all entries with lowest season_eid

for and i am using following query to get ids of them:

Movie.objects.filter(category_type = 2).values('season_eid').annotate(models.Min('season_eid'))

and having id i can get all data for objects using django orm __in construction.

Can I make grouping / annotate and take all fields/values using only one query? values + annotate gives me only list of dictionaries, but instead of this i would like to get proper objects (lowest value/min of season_eid) with rest of fields.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ζ澈沫 2024-08-29 12:59:56
Movie.objects.annotate(category_min_season = models.Min('category__season_id')).filter(season_id=category_min_season)

假设您的类别对电影模型有 FK。

更新:

实际上你甚至不需要注释;感谢您存储在表中的非规范化数据。

你可以这样做:

Model.objects.filter(id=Q(season_id))
Movie.objects.annotate(category_min_season = models.Min('category__season_id')).filter(season_id=category_min_season)

assuming that your catgory has FK to the Movies model.

Update:

Actually you don't even need annotation; thanks to the denormalised data you have stored in the table.

You can just do:

Model.objects.filter(id=Q(season_id))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文