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

时间:2018-11-24 11:37:04

标签: python django lambda

我有约会和一些美元毛额模特:

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.按总量,按2.更新,按3.,但pk不好,

qs1_obj2:1.按毛额计算; 2。但按dpdated来得晚,

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,

我该怎么做?

1 个答案:

答案 0 :(得分:2)

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

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