第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Django:注釋最近外鍵的兩個值

Django:注釋最近外鍵的兩個值

慕姐8265434 2022-09-06 21:26:11
我實際上使用的是python 3.7和Django 3.0.4。我在我的應(yīng)用程序中使用像這樣的 models.py 用于簡單的消息系統(tǒng)。from torii.models import Userclass Room(models.Model):    users = models.ManyToManyField(User,                                   related_name='rooms',                                   blank=True)    name = models.CharField(max_length=100)class Message(models.Model):    room = models.ForeignKey(Room,                             on_delete=models.CASCADE,                             related_name='messages')    user = models.ForeignKey(User,                             on_delete=models.CASCADE)    content = models.TextField()    date = models.DateTimeField(auto_now_add=True)因此,當(dāng)我的用戶發(fā)送消息時,我會創(chuàng)建一個附加到我的.我想查詢給定的所有消息,并注釋查詢中最新消息的日期和最后一條消息。MessageRoomRoomUser沒有問題,在我的相關(guān)消息中獲取最新的日期,如下所示:Maxfor room in Room.objects.filter(users=user).annotate(last_message_date=Max('messages__date')).order_by('-last_message_date'):     print(room.__dict__){'id': 7, 'name': 'room-7', 'last_message_date': datetime.datetime(2020, 3, 20, 14, 0, 2, 118190, tzinfo=<UTC>)}{'id': 9, 'name': 'room-9', 'last_message_date': datetime.datetime(2020, 3, 8, 15, 19, 52, 343780, tzinfo=<UTC>)}{'id': 8, 'name': 'room-8', 'last_message_date': datetime.datetime(2020, 3, 7, 17, 18, 32, 648093, tzinfo=<UTC>)}但是我沒有找到任何方法來簡單地注釋最后一條消息。我試過,但實際上,它是按字母順序排列的消息,并且返回的人總是相同的......我嘗試了幾個子查詢,但它效果不是很好。contentMax('messages__content')FQ如何直接使用查詢注釋 的結(jié)果?room.messages.last().content
查看完整描述

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ù)雜但唯一的請求。


查看完整回答
反對 回復(fù) 2022-09-06
  • 1 回答
  • 0 關(guān)注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號