我希望能够在我的模板中执行以下操作:
request.user.notifications.unseen
向用户显示他所有看不见的通知。
到目前为止,基于我在这里发现的一些帖子,我能够开发出这个:
class NotificationQuerySet(models.QuerySet):
def unseen(self):
return self.filter(is_read=False)
class NotificationManager(models.Manager):
use_for_related_fields = True
def get_query_set(self):
return NotificationQuerySet(self.model)
def unseen(self, *args, **kwargs):
return self.get_query_set().unseen(*args, **kwargs)
它工作正常,但它显示了所有用户的所有“看不见的”通知。
我认为通过指定对象关系(例如user.notifications
),会将参数传递给函数,将结果缩小到请求它的用户。
那么,我如何缩小一个用户而不是所有用户的结果呢?
的 Models.py
class UserNotification(models.Model):
user = models.ForeignKey(User, related_name='notifications')
advertisement = models.ForeignKey(Advertisement)
creation_date = models.DateTimeField(editable=False, default=timezone.now)
notification_type = models.CharField(max_length=3, choices=NOTIFICATION_TYPE)
is_read = models.BooleanField()
objects = NotificationManager()
答案 0 :(得分:1)
sum
在您看来:
class NotificationManager(models.Manager):
def unseen(self,user):
queryset = super(NotificationManager,self).get_queryset()
queryset = queryset.filter(user=user,is_read=False)
return queryset
class UserNotifications(models.Model):
... same fields ...
objects = NotificationManager()
您将获得一个可以进一步过滤的查询集,使用all(),get()等,就像任何其他查询集一样。向此管理器添加args,kwargs和更多方法,而通用对象管理器不会更改。