[英]How do I collect multiple Django models together into a single list?
我在Django中有一个相当简单的博客,其中有用于Article和Link的单独模型。 我想在我的模板中有一个循环,按日期顺序将它们都列出,这意味着像这样:
def listview(request):
return render_to_response('index.dtmpl', {
'articles' : ArticlesAndLinks.objects.order_by('post_date')[:10]
}, context_instance = RequestContext(request)
我不确定该怎么做。 我是否必须分别获取Articles.objects.order_by('post_date')
和Links.objects.order_by('post_date')
,将它们合并并重新排序? 还是有一种更好的Django-ish / Pythonic方法来实现这一目标?
如果有帮助,则Posts和Links都是抽象类Post的子类,但是由于它是一个抽象类,因此看来我无法在其上运行集合。
事实证明,解决方案是将抽象类变成一个真正的类,然后我可以收集它。
好吧,最明显的答案是让Post具体课程。 否则,您可能不得不压缩ORM并采用手工编码的SQL或手动合并/排序两个查询集。 鉴于数据集的大小,我将选择最后一个解决方案。
重构可能是更好的解决方案,但这是另一个可以完成此工作的解决方案:
创建一个自定义管理器:
class PostManager(models.Manager):
def mixed(self, first):
all_dates = []
articles_dates = Articles.objects.extra(select={'type':'"article"'}).values('id', 'post_date', 'type').order_by('-post_date')[:first]
links_dates = Links.objects.extra(select={'type':'"link"'}).values('id', 'post_date', 'type').order_by('-post_date')[:first]
all_dates.extend(articles_dates)
all_dates.extend(links_dates)
# Sort the mixed list by post_date, reversed
all_dates.sort(key=lambda item: item['post_date'], reverse=True)
# Cut first 'first' items in mixed list
all_dates = all_dates[:first]
mixed_objects = []
mixed_objects.extend(Articles.objects.filter(id__in=[item['id'] for item in all_dates if item['type'] = 'article']))
mixed_objects.extend(Links.objects.filter(id__in=[item['id'] for item in all_dates if item['type'] = 'link']))
# Sort again the result list
mixed_objects.sort(key=lambda post: post.post_date, reverse=True)
return mixed_objects
并在您的抽象模型中使用它:
class Post(models.Model):
class Meta:
abstract = True
objects = PostManager()
然后,您的混合对象的调用将是:
Article.objects.mixed(10)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.