我很难构建一个查询(sqlite)来获取用户所属的每个聊天室的最新消息。这是我在 Django 中的模型:
class Membership(models.Model):
room_name = models.TextField()
members = models.ManyToManyField(CustomUser, through="Message")
class Message(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
room = models.ForeignKey(Membership, on_delete=models.CASCADE)
advertisement = models.ForeignKey(Advertisement, on_delete=models.CASCADE, default=None)
message = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
class CustomUser(AbstractUser):
username = models.CharField(max_length=200, unique=False)
现在考虑到这一点,我想显示用户所属的所有房间以及房间中的最新消息。我感觉我已经很接近了:
select *
from chat_message as cm
inner join (select max(id) as lm from chat_message group by room_id) as last_messages on last_messages.lm = cm.id
inner join main_advertisement ma on cm.advertisement_id = ma.id
inner join chat_membership as cmb ON cm.room_id = cmb.id
order by id;
这看起来为我提供了每个房间的最新消息(和其他数据),但现在我很难过滤 1 个用户(例如 user_id = 3)。
任何想法,以及如何在 django ORM 中开始构建它的可能提示,我们将不胜感激。
您可以向内部查询添加一个过滤器,您可以在其中获得最大
chat_message
ids:
select *
from chat_message as cm
inner join (select max(id) as lm from chat_message where user_id = 3 group by room_id) as last_messages on last_messages.lm = cm.id
inner join main_advertisement ma on cm.advertisement_id = ma.id
inner join chat_membership as cmb ON cm.room_id = cmb.id
order by id;