对于以下unread
定义,如何让当前用户能够计算给定用户的MessageThread数量?
class MessageThread(models.Model):
subject = models.CharField(max_length=256, blank=False)
def unread(self):
return self.objects.filter(***messagerecipient__recipient='current user'***).distinct().count()
class MessageRecipient(models.Model):
message = models.ForeignKey(Message)
recipient = models.ForeignKey(User)
status = models.CharField(max_length=20, choices=MESSAGE_STATUS, default="unread")
答案 0 :(得分:1)
您必须将请求传递给方法:
def unread(self, request):
return self.objects.filter(messagerecipient__recipient=request.user).distinct().count()
但这没有意义,因为你正在调用模型方法(对特定行进行操作,即单个MessageThread) - 你应该编写一个模型管理器来操作整个表(即查找所有未读的线程)表MessageThread)
class MessageThreadManager(models.Manager):
def get_unread_threads(self, user):
return self.objects.filter(messagerecipient__recipient=user).distinct()
class MessageThread(models.Model):
objects = MessageThreadManager()
所以现在你可以打电话:
unread_threads = MessageThread.objects.get_unread_threads(some_user_obj)