python - 注释每个用户的计数,然后按最近出现的日期排序

标签 python django

我想获取每个 user_from 的未读消息数,这些消息按她/他的最后一条消息的日期排序。

class Chat(models.Model):
    user_from = models.ForeignKey(settings.AUTH_USER_MODEL)
    user_to = models.ForeignKey(settings.AUTH_USER_MODEL)
    is_read = models.BooleanField(default=False)
    added_on = models.DateTimeField(auto_now_add=True)
    message = models.CharField(max_length=255)

我正在寻找一些像这样输出的查询集:

输出查询集:

enter image description here

最佳答案

from django.db.models import Count, Max
query_set = Chat.objects.values('user_from').annotate(unread_count=Count('user_from')).filter(is_read=False).annotate(last_time=Max('added_on')).order_by('-last_time')

关于python - 注释每个用户的计数,然后按最近出现的日期排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56626883/

相关文章:

python - 在功能上,torch.multinomial 与 torch.distributions.categorical.Categorical 相同吗?

django - 如何创建 Django 项目文件夹

python - Zeep 客户端抛出 Service has no operation 错误

带有 unicode 文件名的 python-requests post

python - 如何在solve_bvp中设置适当的边界条件?

python - 列表上的 Django lte/gte 查询

python - Django Python 休息框架,在 chrome 中请求的资源上不存在 'Access-Control-Allow-Origin' header ,在 firefox 中工作

python - 子类化 listview 以将多个 View 引用到一个模板 django

python - DRF_YASG 生成的文档内的自由格式文本

c++ - Double 或 float - 优化例程