我的模型:
class PromoNotification(models.Model):
title = models.CharField(_('Title'), max_length=200)
content = models.TextField(_('Content'))
users = models.ManyToManyField(User, blank=True, null=True)
groups = models.ManyToManyField(Group, blank=True, null=True)
我想将项目发布到具有某些权限的模板。该模板仅显示列表中用户(用户或/和组)的通知。我应该怎么办?感谢您的任何帮助。如果可以,请告诉我一些代码。
请您参考如下方法:
您可以使用自定义管理器,这样可以更轻松地在多个 View 中进行用户过滤。
class PromoNotificationManager(models.Manager):
def get_for_user(self, user)
"""Retrieve the notifications that are visible to the specified user"""
# untested, but should be close to what you need
notifications = super(PromoNotificationManager, self).get_query_set()
user_filter = Q(groups__in=user.groups.all())
group_filter = Q(users__in=user.groups.all())
return notifications.filter(user_filter | group_filter)
将经理连接到您的 PromoNotification 模型:
class PromoNotification(models.Model):
...
objects = PromoNotificationManager()
那么在你看来:
def some_view(self):
user_notifications = PromoNotification.objects.get_for_user(request.user)
您可以在文档中阅读有关自定义管理器的更多信息:http://www.djangoproject.com/documentation/models/custom_managers/
