按日期排序 2 个不同的查询集

Order 2 different querysets by date

这是一个简单的问题,我可以通过for循环和大量比较来实现,但我想知道是否有更好的方法。

我有两个查询集:

  comments = Comment.objects.all()
  actions = Action.objects.all()

因此,我需要一个包含按日期排序的评论和操作的列表。 Comment 模型和 Action 模型有一个日期 (date=models.DateTimeField(auto_now_add=True)) 字段。

换句话说:

wall = [] # Alternate Comments and Actions ordered by date

这正是 Django ORM 擅长的地方!

https://docs.djangoproject.com/en/1.8/topics/db/queries/#retrieving-specific-objects-with-filters

comments = Comment.objects.order_by('date')
actions = Actions.objects.order_by('date')

然后您可以遍历这两个列表,因为它们已经按日期排序,您只需要对每个元素进行一次成对比较即可按日期对它们进行排序!

您可以拥有组合评论和操作的列表

comments = Comment.objects.all()
actions = Action.objects.all()
from itertools import chain
wall = list(chain(comments, actions))

然后您可以按属性对 python 对象列表进行排序,在您的例子中是日期

wall.sort(key=lambda x: x.date)

您还可以在 lambda 函数中传递反向 True/False,用于降序和升序

wall.sort(key=lambda X:x.date, reverse=True)