2010-08-04 24 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