我有一个这样的数据库模型:
class RssNewsItem(models.Model):
title = models.CharField(max_length=512)
description = models.TextField()
image_url = models.CharField(max_length=512)
published = models.DateTimeField(auto_now=True)
url = models.CharField(max_length=512, default='')
author = models.CharField(max_length=128, default='')我想通过选择3个新闻项目和7个其他作者的项目(列出10个新闻项目)来“提升”某个作者,并通过-published对它们进行排序。推广的新闻项目在列表中的位置无关紧要。数字也不重要。它只是必须是推广的新闻-项目占列表的30%。
假设我想推广'author1‘,我的网站上总共有6个作者。
对于Django,这是可能的吗?(我希望避免遍历列表或查询集)
发布于 2013-06-21 18:10:14
from itertools import chain
q1 = RssNewItem.objects.filter(author="author1").order_by("-published")[:3]
q2 = RssNewItem.objects.exclude(author="author1").order_by("-published")[:7]
q = list(chain(q1, q2))附注:这是关于合并查询集的一个很好的答案:
How to combine 2 or more querysets in a Django view?
list(q1).extend(list(q2))。与上面的问题相同,但速度更慢。q = q1 | q2以将它们保留为QuerySet。发布于 2013-06-21 18:14:24
class RssNewsItemManager(models.Manager):
def get_rsslist_with_promoted(self,auth):
prom=self.objects.filter(author=auth).order_by("-published")[:3]
unprom=self.objects.exclude(author=auth).order_by("-published")[:7]
return prom|unprom
class RssNewsItem(models.Model):
title = models.CharField(max_length=512)
description = models.TextField()
image_url = models.CharField(max_length=512)
published = models.DateTimeField(auto_now=True)
url = models.CharField(max_length=512, default='')
author = models.CharField(max_length=128, default='')
objects = RssNewsItemManager()发布于 2013-06-21 18:14:35
10个项目或任何少量项目的解决方案:
qs = RssNewsItem.objects.order_by('-published')
promoted = list(qs.filter(author=promoted_author)[:count_of_promoted])
to_fill = list(qs.exclude(author=promoted_author)[:total_count-len(promoted)])
to_return = sorted(promoted + to_fill, key=lambda rni: -rni.published)
return to_returnhttps://stackoverflow.com/questions/17232529
复制相似问题