2010-08-04 49 views
1

我的模型限制用户:Django的 - 谁查看的项目

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) 

我要发布一些有意思的东西与一些权限模板。该模板仅显示列表中用户的通知(用户或/和组)。我该怎么办?感谢您的任何帮助。如果可以,请给我看一些代码。

+0

您希望编写一个视图,其中只有属于某个组的某些用户或用户才能查看PromoNotificatio n信息?如果是这样,提供用户和组的模型描述将有很大帮助。 – 2010-08-04 12:42:57

回答

3

您可能会使用自定义管理器,这可以更轻松地在多个视图中执行此用户筛选。

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/

+0

一些错误,但这是一个好主意。谢谢! group_filter = Q(groups__in = user.groups.all()) user_notifications = PromoNotification.objects.get_for_user(request.user) – anhtran 2010-08-04 16:49:23

+0

感谢您发布您找到的错误。我已经更新了答案以包含您的修复程序。 – 2010-08-05 15:13:57