我正在建立一个论坛,一个人发布一条消息,其他几个人回复它。
我有一个消息模型和一个响应模型如下:
class Messages (models.Model):
author = models.ForeignKey(User)
message = models.TextField()
def __unicode__(self):
return self.message
class Responses (models.Model):
message = models.ForeignKey(Messages)
responder = models.ForeignKey(User, related_name='responder')
rsp_to = models.ForeignKey(User, related_name='rsp_to')
rsp_from = models.ForeignKey(User, related_name='rsp_from')
response = models.TextField()
pub_date = models.DateTimeField('date_published')
def __unicode__(self):
return self.message
我想获得一个根据响应者组织的查询集,以便来自最新响应者的所有响应都是第一个,第二个最新响应者的响应是第二个,依此类推。
示例数据库表:
pk message responder rsp_to rsp_from response pub_date
------------------------------------------------------------
1 a User.2 a.author User.2 .... 1
2 a User.3 a.author User.3 .... 2
3 a User.3 User.3 a.author .... 3
4 a User.4 a.author User.4 .... 4
5 a User.4 User.4 a.author .... 5
6 a User.2 User.2 a.author .... 6
7 a User.3 a.author User.3 .... 7
8 a User.3 User.3 a.author .... 8
9 a User.4 a.author User.4 .... 9
重新排序的查询集:
pk message responder rsp_to rsp_from response pub_date
------------------------------------------------------------
9 a User.4 a.author User.4 .... 9
5 a User.4 User.4 a.author .... 5
4 a User.4 a.author User.4 .... 4
8 a User.3 User.3 a.author .... 8
7 a User.3 a.author User.3 .... 7
3 a User.3 User.3 a.author .... 3
2 a User.3 a.author User.3 .... 2
6 a User.2 User.2 a.author .... 6
1 a User.2 a.author User.2 .... 1
或者表示为:
r = [<all responses from latest responder>, <all responses from 2nd latest responder>,..., <all responses from earliest responder>]
如果我开始:
r = Responses.objects.filter(message="a").order_by('-pub_date')
我先得到最新的回复。如何重新排序查询集,以便来自最新的唯一响应者的所有响应在查询集中首先分组,来自第二个唯一响应者的所有响应都在第二个分组,等等?