1 回答

TA貢獻(xiàn)1946條經(jīng)驗 獲得超3個贊
最后,我使用并記錄在那里解決了這個問題。OuterRefSubquery
from django.db.models import Max, OuterRef, Subquery
newest = Message.objects.filter(room_id=OuterRef('pk')).order_by('-date')
for room in Room.objects.filter(users=user)
.annotate(last_message_date=Max('messages__date'),
last_message=Subquery(newest.values('content')[:1]))
.order_by('-last_message_date'):
print(r.__dict__)
根據(jù)我對行為的理解,我們事先準(zhǔn)備說使用將子查詢調(diào)用到濾子元素的元素,然后按 進(jìn)行排序。因此,它返回最新的元素,我們采用 of 字段來注釋它。Subqueryidannotate-datevaluecontent
這將使用數(shù)據(jù)庫的所有性能創(chuàng)建一個復(fù)雜但唯一的請求。
添加回答
舉報