如果自己拼sql
mysql就
select * from (
SELECT * FROM test.sleep_news order by -date)
as Subquery group by cat_id;
其他如果有with的就更好弄了,写得可以更美一些。
要是不在乎查询多次的话直接
results = {}
Categories = Category.objects.all()
for category in Categories:
news = News.objects.filter(cat=category).order_by('-date')[0]
results[category] = news
有些云服务居然是用查询sql次数来收费的我就不吐槽了。。