Django:获得manytomanyfield的最后一项

时间:2016-02-14 10:44:28

标签: python django django-models

使用这些模型:

def .. :
    u = request.user
    conversations = Conversation.objects.filter(Q(creatorr=u)|Q(destinataire=u)).annotate(nbMsg=Count('messages'),date=Max('messages__date_send')).order_by('date','id')

因此,对于每次对话,我都希望创建最后一个MessagePerso的文本(Conversation中的ManyToManyField)和其他信息。

所以现在,我有这个:

{{1}}

我没有为每个对话创建最后一条消息的文本,是怎么做到的?

1 个答案:

答案 0 :(得分:1)

您可以按date_send字段升序订购数据,如下所示:

class Message(models.Model):
    text = models.CharField(max_length=200)
    date_send = models.DateTimeField(auto_now_add=True,editable=False)
    emeteur = models.ForeignKey(User,null=True,related_name="+")

    class Meta :
        abstract = True
        ordering = ['date_send'] # default ordrer while fetching data

对于每个对话的消息,您使用.last()获取最后一个消息:

def .. :
    u = request.user
    conversation_id_list = Conversation.objects.filter(Q(creatorr=u)|Q(destinataire=u)).values_list('id', flat=True)
    message_list = list(()
    for id in conversation_id_list:
        last_message = MessagePerso.objects.filter(conversation_id=id).last()
        message_list.append(last_message)
        print(last_message.text)

如果会话数量很大并且您希望最小化数据库查询,则可以使用prefetch_related

def .. :
    u = request.user
    conversation_list = Conversation.objects.filter(Q(creatorr=u)|Q(destinataire=u)).preftech_related('messages')
    messages_dict =dict()
    for conversation in conversation_list:
        messages_dict.update({
            converstaion.id: conversation.messages.all()
        })
    last_message_list = list()
    for conversation_id, message_list in messages_dict.items():
        if message_list:
          last_message = messages_dict.get(conversation_id)[len(message_list) -1:]
          last_message_list.append(last_message)
          print(last_message.text)