【问题标题】:Sum two query set in django在 django 中对两个查询集求和
【发布时间】:2013-06-13 19:58:58
【问题描述】:

我有两个模型,Quote 和 Post。 我想要两个将此发送到我的模板:

posts = Post.objects.order_by("-submitted_time")
quotes = Quote.objects.order_by("-submitted_time")

thing = posts + quotes

但是有些两个QuerySet 不支持。如何将帖子和报价发送到模板?

假设我在数据库中有两个 Post 和两个 Quote,如下所示:

   post 1        submitted_time:2010/2/12
   post 2        submitted_time:2010/2/8 
   quote 1       submitted_time:2010/2/9
   quote 2       submitted_time:2010/2/13

我想发送一个类似[quote2, post1, quote1, post2]的列表

【问题讨论】:

    标签: django django-models django-queryset


    【解决方案1】:

    你可以这样做:

    from itertools import chain
    thing = list(chain(posts, quotes))
    

    按您想要的方式订购:

    import operator
    from itertools import chain
    
    thing = list(chain(posts, quotes))
    thing = sorted(thing, key=operator.attrgetter('submitted_time', reverse=True)
    

    或者

    thing = sorted(thing, key=operator.attrgetter('submitted_time')
    

    取决于你想要的

    【讨论】:

    • 谢谢。我想要你说的事情清单。
    • 然后去掉最后的reverse参数。检查编辑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 2017-12-04
    • 2022-01-13
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2021-11-10
    相关资源
    最近更新 更多