在不同名称的字段上对两个不同的模型进行排序

2024-09-29 21:30:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个模型:PostType1PostType1。在

class PostType1(models.Model):
    ...
    created_date = models.DateTimeField(_('created date'), blank=True, null=True)

class PostType2(models.Model):
    ...
    publish_date = models.DateTimeField(_('publish date'), blank=True, null=True)

我对这两个问题进行了查询:

^{pr2}$

我知道怎么把它们拴起来:

posts = chain(posts_type1,posts_type2)

我正在寻找一种按日期降序排序的方法。
这可能吗?还是让我看看原始sql?在


Tags: 模型truedatemodelmodelspublishnullclass
2条回答

每个查询都可以使用order_by执行排序:

posts_type1 = PostType1.objects.all().order_by('-created_date')
posts_type2 = PostType2.objects.all().order_by('-publish_date')

如果希望对整个结果进行排序,可以使用自定义迭代器而不是chain。仅两种型号的示例(尽管不一定是最干净的型号):

^{pr2}$

StefanoP建议使用sorted也可以,但它会在排序过程中从数据库中检索所有项目,这可能是也可能不是您关心的问题。在

因此,如果您的计划是对两个查询集的并集进行排序,则必须使用sorted方法。我会喜欢这样的东西:

sorted(chain(posts_type1, posts_type2), 
       key=lambda x: x.created_date if isinstance(x, PostType1) 
                                    else x.publish_date)

相关问题 更多 >

    热门问题