V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
banks0913
V2EX  ›  Django

diango model 如何实现某个字段的每个类别取前几个?

  •  
  •   banks0913 · Jun 15, 2015 · 4319 views
    This topic created in 3974 days ago, the information mentioned may be changed or developed.

    小弟对django和数据库都不是很熟,目前遇到以下问题:

    数据表中有新闻表(news table),字段包含新闻标题(),内容,类别(category)等
    如:
    news table:{
    title
    content
    category
    publish_time
    .......
    }

    其中category(类别)有“科技”“体育”“数码”“影视”等。

    如何取出每种类别按照时间排序的前3条记录???
    如果依次去取岂不是效率很低 ?

    aggron
        2
    aggron  
       Jun 15, 2015
    用原生的sql查询,我猜你用的数据库是mysql,"limit in sub query"在mysql中不支持,所以得用
    @blueset 提供的方法。
    换postgresql吧:
    select * from news n where id in (select id from news n2 where n.category=n2.category order by publish_time desc limit 3)
    多么容易懂的方式
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2259 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 00:22 · PVG 08:22 · LAX 17:22 · JFK 20:22
    ♥ Do have faith in what you're doing.