在不同命名的字段上排序两个不同的模型(Sort two different models on differently named fields)

我有两个模型: PostType1 , PostType1 。

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)

我查询两个:

posts_type1 = PostType1.objects.all() posts_type2 = PostType2.objects.all()

我知道如何链接它们:

posts = chain(posts_type1,posts_type2)

我正在寻找一种按日期降序排序的方法。 这可能吗 ? 或者我应该看看原始的SQL?

I have two models: PostType1, PostType1.

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)

I make a query for both getting:

posts_type1 = PostType1.objects.all() posts_type2 = PostType2.objects.all()

I know how to chain them:

posts = chain(posts_type1,posts_type2)

I'm looking for a way to sort them by date descending. Is this possible ? Or shall I look to raw sql?

最满意答案

因此,如果您的计划是对两个查询集的并集进行排序,则必须使用sorted方法。 我会去做类似的事情:

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

So, if your plan is to sort the union of the two querysets, you have to use the sorted method. I would go for something like:

sorted(chain(posts_type1, posts_type2), key=lambda x: x.created_date if isinstance(x, PostType1) else x.publish_date)在不同命名的字段上排序两个不同的模型(Sort two different models on differently named fields)

我有两个模型: PostType1 , PostType1 。

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)

我查询两个:

posts_type1 = PostType1.objects.all() posts_type2 = PostType2.objects.all()

我知道如何链接它们:

posts = chain(posts_type1,posts_type2)

我正在寻找一种按日期降序排序的方法。 这可能吗 ? 或者我应该看看原始的SQL?

I have two models: PostType1, PostType1.

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)

I make a query for both getting:

posts_type1 = PostType1.objects.all() posts_type2 = PostType2.objects.all()

I know how to chain them:

posts = chain(posts_type1,posts_type2)

I'm looking for a way to sort them by date descending. Is this possible ? Or shall I look to raw sql?

最满意答案

因此,如果您的计划是对两个查询集的并集进行排序,则必须使用sorted方法。 我会去做类似的事情:

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

So, if your plan is to sort the union of the two querysets, you have to use the sorted method. I would go for something like:

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