2010-08-04 4 views
1

내 모델을 볼 수 제한 사용자 :장고 - 항목을

좀 권한을 가진 템플릿이 항목을 게시 할
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를 볼 수있는보기를 작성하려고합니다. 정보? 그렇다면 사용자 및 그룹의 모델 설명을 제공하면 많은 도움이됩니다. –

답변

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

+0

발견 한 실수를 게시 해 주셔서 감사합니다. 수정 사항을 포함하도록 답변을 업데이트했습니다. –