我有一个对象列表列表:
[
[obj1, obj2, obj3],
[obj4, obj5, obj6], ...
]
object是一个具有日期的实例(从django的queryset返回)。现在我想根据每个对象列表的最新日期来排序outter列表(因为每个列表可以有一个或多个对象,我希望得到最新的日期作为整个集合的表示)。
答案 0 :(得分:1)
假设对象属于dict
类型且具有名为 date 的可比较密钥:
sorted_list = sorted(l, key=lambda items: max(map(itemgetter('date'), items)))
输入生成的完整示例:
from datetime import datetime
from operator import itemgetter
N = 3
M = 4
l = []
for i in range(N):
l.append([])
for j in range(M):
l[-1].append({'date': datetime.now()})
sorted_list = sorted(l, key=lambda items: max(map(itemgetter('date'), items)))
如果我们设置M = N = 2
,则会产生:
[
[{'date': datetime.datetime(2017, 2, 28, 13, 14, 15, 172018)},
{'date': datetime.datetime(2017, 2, 28, 13, 14, 15, 172052)}],
[{'date': datetime.datetime(2017, 2, 28, 13, 14, 15, 172062)},
{'date': datetime.datetime(2017, 2, 28, 13, 14, 15, 172068)}]
]
答案 1 :(得分:1)
假设每个对象都具有date
datetime.date
属性
def sort_by_date(object_lists):
def max_date(objects):
return max(objects, key=lambda obj : obj.date ).date
return sorted(object_lists, key=max_date, reverse=True)
答案 2 :(得分:0)
使用排序属性 例如
class News(models.Model):
news_titles = models.CharField(max_length=200, unique=True)
news_preview = models.CharField(max_length=200, , unique=True)
news_icon = FileBrowseField(u'News icon', max_length=200, directory="IconImages/",
extensions=[".jpg", ".jpeg", ".png", ".gif"],
blank=True,null=True)
enabled = models.BooleanField(default=1)
news_pub_time = models.DateTimeField(_("Published from"),
help_text=_("With Published chosen, won't be shown until this time"),
blank=True, null=True, db_index=True)
news_full_text = models.TextField(max_length=10000,verbose_name=u'Full text')
def __unicode__(self):
return self.news_titles
class Meta:
ordering = ["-news_pub_time"]
verbose_name = u'News'