Django orm最新数据

Django orm latest data

reference

class Board(model.Model):
    master = models.ForeignKey(User, on_delete=models.CASCADE)
    member = models.ForeignKey(User, on_delete=models.CASCADE)
    status = models.PositiveIntegerField(default=0)

class MSG(models.Model):
    Board= models.ForeignKey(Board, on_delete=models.CASCADE)
    writer = models.ForeignKey(User, on_delete=models.CASCADE)
    text = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True, null=True)

如何从这个关系中获取以下值?

我正在使用 PostgreSQL

response = {
    master="USER1",
    member="USER2",
    status=0,
    master_latest_MSG="master last_msg"
    master_latest_date="2020.03.21",
    member_latest_MSG="member last_msg"
    member_latest_date="2020.03.22",
}

有没有比子查询更好的方法?

所有板块的最新消息,板块信息为必填项

response = [
   {
        master="USER1",
        member="USER2",
        status=0,
        master_latest_MSG="master last_msg"
        master_latest_date="2020.03.21",
        member_latest_MSG="member last_msg"
        member_latest_date="2020.03.22",
   },
   {
        master="USER3",
        member="USER4",
        status=0,
        master_latest_MSG="master last_msg"
        master_latest_date="2020.03.23",
        member_latest_MSG="member last_msg"
        member_latest_date="2020.03.23",
   },
]

已编辑,因为“新”Q 部分

在可读但不是性能最佳的方法中,您可以使用 latest and F expressions 获取 board 的数据:

from django.db.models import F

def GetBoardData(board):

  data = (
    MSG
    .objects
    .filter(board = board)
  )

  latest_master = (
    data
    .filter(writer=F('board__master')) #<--- using F
    .latest('created_at')              #<--- using latest 
  )

  latest_member = (
    data
    .filter(writer=F('board__member'))
    .latest('created_at')
  )
  
  # be carefull, latest_member and latest_master can be None
  return {
    master=latest_master.writer.username,
    member=latest_member.writer.username,
    status=board.status,
    master_latest_MSG=latest_master.text
    master_latest_date=latest_master.created_at,
    member_latest_MSG=latest_member.text
    member_latest_date=latest_member.created_at,
  }

并为每个板调用函数:


response = [
   GetBoardData(board)
   for board in Board.objects.all()
]

对于性能优化方法,使用 window functions

随心所欲format dates