class Post(models.Model):
title = ...
category = models.ForeignKey(Category)
date = .......
class Category(models.Model):
title = ....
在主页上我想显示5个员额与最新的日期查询最新的帖子,但所有职位必须是从不同的类别。例如,有50个分类。可能吗?Django的:从不同类别
class Post(models.Model):
title = ...
category = models.ForeignKey(Category)
date = .......
class Category(models.Model):
title = ....
在主页上我想显示5个员额与最新的日期查询最新的帖子,但所有职位必须是从不同的类别。例如,有50个分类。可能吗?Django的:从不同类别
from django.db.models import Max
categories = Category.objects.annotate(most_recent=Max(post__date)).order_by('-most_recent')[:5]
posts = list()
for category in categories:
posts.append(category.post_set.latest())
,随着最近张贴的日期为most_recent
的价值,然后你就可以为了通过获得5个最注释的类别最近的类别。
然后,只需遍历各个类别并为每个类别提取最新的帖子。完成。
+1最干净的回答 –
+1对我来说很漂亮 –
你敢打赌这是可能的。
随机选择5个大类
抓住最近的职位为每个类别
也许是这样的:
randposts = {} #list for most recent posts of 5 randomly selected categories
for randomcat in Category.objects.order_by('?')[5:]:
randposts.add(Post.objects.filter(category = randomcat).order_by('date')[0])
这可能会帮助:https://docs.djangoproject.com/en/dev/ref/models/querysets/
好吧,让我们再次尝试这个..
catsused = {}
posts = {}
postindex = 0
posts.add(Post.objects.order_by('date')[postindex])
catsused.add(Post.objects.order_by('date')[postindex].category
for each in range(1,5):
postindex = postindex + 1
post = Post.objects.order_by('date')[postindex]
while post.category in catsused:
postindex = postindex + 1
post = Post.objects.order_by('date')[postindex]
posts.add(post)
catsused.add(post.category)
posts ## Now contains your posts
对我来说,这看起来像可怕的代码,但我想接近这一点的东西可以完成这项工作。你会想要添加一些代码来处理“postindex”,以查看系统中的帖子数量。
荡涤的文件的代码版本:
catsused = {}
posts = {}
for post in Post.objects.order_by('date'):
if post.category not in catsused:
posts.add(post)
catsused.add(post.category)
if len(catsused) == 5:
break
非常酷......:D –
使用order_by和:
Post.objects.all().order_by('category', 'date').distinct('category')
然后对category
和date
领域的表现将指数一起。
但我认为真正的生产方式是使用Redis
缓存和更新ID的最新类别的职位列表。
难道你不能查询5个最近更新的类别,然后从这些类别中获取顶部的帖子? –
没有字段“更新时间”类别...或者你的意思是,我可以以某种方式通过查询检索它? – Friendka