我有以下两种模式:
class OrderItem(models.Model):
order = models.ForeignKey(Order, related_name='items')
title = models.ForeignKey(Title, related_name='order_items')
class OrderNotes(models.Model):
order_item = models.ForeignKey('OrderItem', blank=True, null=True)
timestamp = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
我如何按最近的OrderItem
活跃排序OrderNote
?
在pseudo_code中:
OrderItem.objects.order_by('ordernotes_set.order_by('is_active', '-timestamp'))
答案 0 :(得分:0)
我认为你可以使用注释来轻松处理这个问题。 https://docs.djangoproject.com/en/dev/topics/db/aggregation/#following-relationships-backwards
from django.db.models import Max
OrderItems.annotate(newest_note_time=Max('ordernotes__timestamp'))
.order_by('-ordernotes__is_active', '-newest_note_time')