基于FK属性的复杂django db排序(Complex django db ordering based on FK properties)
我有以下两种型号:
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)如何通过最新的OrderNote对OrderItem进行排序?
在伪代码中:
OrderItem.objects.order_by('ordernotes_set.order_by('is_active', '-timestamp'))?
I have the following two models:
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)How would I sort OrderItems by the most recent OrderNote that is active?
In pseudo_code:
OrderItem.objects.order_by('ordernotes_set.order_by('is_active', '-timestamp'))?
最满意答案
我认为你可以使用注释来相当容易地处理这个问题。 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')I think you could use annotations to handle this fairly easily. 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')更多推荐
发布评论