我有这样的数据库模型:
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有可能吗? (我想避免迭代列表或查询集)
答案 0 :(得分:3)
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))
P.S。这是关于合并查询集的一个很好的答案:
How to combine 2 or more querysets in a Django view?
list(q1).extend(list(q2))
。与上述问题相同且速度较慢。 q = q1 | q2
将它们保存为QuerySet。 答案 1 :(得分:1)
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()
答案 2 :(得分:0)
解决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_return