gpt4 book ai didi

python django 使用 lambda 和 if 语句进行排序

转载 作者:行者123 更新时间:2023-12-01 01:24:54 24 4
gpt4 key购买 nike

我有日期和一些美元总模型:

class FirstDate(models.Model):
gross = models.DecimalField(max_digits=12, decimal_places=2, default=0)
updated = models.DateTimeField(auto_now=True)

class SecondDate(models.Model):
gross = models.DecimalField(max_digits=12, decimal_places=2, default=0)
updated = models.DateTimeField(auto_now=True)

并且想按gross排序,如果gross相同,则用updated字段排序

例如,

qs1 = SoloDate.objects.all()[:2]
qs2 = GroupDate.objects.all()[:2]

result_list = sorted(
chain(qs1, qs2),
key=lambda x: x.gross # and if gross is the same, for the gross same objects, x.updated and then update was also the same, x.pk,
reverse=True
)

我的意思是,有两个对象分别来自 qs1 和 qs2。

# objects from qs1
qs1_obj1 = {
'pk': 1,
'gross': 5,
'updated': 2018-11-24 10:53:23.360707+00:00
}

qs1_obj2 = {
'pk': 2,
'gross': 5,
'updated': 2018-11-25 10:53:23.360707+00:00
}

# objects from qs2
qs2_obj1 = {
'pk': 3,
'gross': 5,
'updated': 2018-11-24 10:53:23.360707+00:00
}

qs2_obj2 = {
'pk': 4,
'gross': 1,
'updated': 2018-11-23 10:53:23.360707+00:00
}

result_list 顺序为 qs1_obj1qs2_obj1qs1_obj2qs_2_obj_2 .

原因是:

qs1_obj1:1.按总量,2.按更新,3.按PK,

qs2_obj1:1.by总,2.by更新,3.但pk不好,

qs1_obj2:1.bygross,2.butbydpdated迟到了,

qs2_obj2:1.gross很小。

也许这不是一个好问题或麻烦的问题,我需要帮助。

问题是:

key=lambda x: x.gross # and if gross is the same, for the same gross objects, x.updated and then update was also the same, x.pk,

我该怎么做?

最佳答案

尝试按多个字段排序,如下所示:

result_list = sorted(
chain(qs1, qs2),
<b>key=lambda x: (x.gross, -x.updated.timestamp(), x.pk)</b> # and if gross is the same, for the gross same objects, x.updated and then update was also the same, x.pk,
reverse=True
)

关于python django 使用 lambda 和 if 语句进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53457718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com