2013-03-04 190 views
1

在我的項目管理應用程序中,我有一個列出db中所有項目的頁面。我希望它可以過濾項目,例如只顯示用戶是管理員的項目。下面模板中的代碼根據用戶點擊的內容,使用不同的參數調用project_list視圖。根據arg篩選結果

我需要幫助的是以下視圖中的箭頭指向的查詢,即僅顯示用戶是成員的項目以及用戶既不是管理員也不是成員的所有項目。

模板:

<h5>Show only projects where you are:</h5> 
<div id="filter_div"> 
    <a class="btn btn-success" href="{% url project_list 'admin' %}">Admin</a> 
    <a class="btn btn-info" href="{% url project_list 'member' %}">Member</a> 
    <a class="btn" href="{% url project_list 'not_member' %}">Not member</a> 
</div> 

視圖:

def project_list(request, projects_to_show='All'): 
    if projects_to_show == 'admin': 
     projects = get_list_or_404(Project.objects.filter(added_by_user = user)) 
    else: 
     if projects_to_show == 'member': 
      projects = get_list_or_404(?) // <- only projects where user is a member 
     else: 
      if projects_to_show == 'not_member' : 
       projects = get_list_or_404(?) // <----- only projects where user is NOT admin OR member 

     projects = get_list_or_404(Project.objects.order_by('name')) // <- all projects (works) 

    return render(request, 'projects/list.html', {"projects" : projects, "headline" : "All projects"}) 

模型 '項目' 和 '用戶' 具有許多一對多關係(即表project_users存在於數據庫中)。這是該項目模型:

class Project(models.Model): 
    ... the rest of the fields... 
    added_by_user = models.ForeignKey(User) 
    users = models.ManyToManyField(User, related_name='projects') 

回答

1

低於更正:過濾器應設置是這樣的...(我相應的修改文本)

users__id__iexact=user.id 

projects_to_show == 'member'查詢應該是這樣的:

projects = Projects.objects.filter(users__id__iexact=user.id) 

思考最後一個,projects_to_show == 'not_member'我想這可能工作:

projects = Projects.objects.exclude(users__id__iexact=user.id) 

要排除用戶和added_by_user,只需添加一個額外的排除。 E.g:

projects = Projects.objects.exclude(users__id__iexact=user.id) 
projects = projects.exclude(added_by_user=user) 

或者作爲一個說法,這應該工作:

projects = Projects.objects.exclude(users__id__iexact=user, added_by_user=user) 

過濾器是一個字段查找。 The django details.

+0

非常感謝!最後一個 - 是否會排除用戶是管理員或成員的項目? – holyredbeard 2013-03-04 19:10:54

+0

試試這個:'projects = Projects.objects.exclude(users__iexact = user,added_by_user__iexact = user)'。您也可以簡單地過濾項目:'projects.exclude(added_by_user__iexact = user)'。可能不需要使用'added_by_user__iexact = user',因爲該表達式簡化爲'added_by_user = user',例如。 'projects.exclude(added_by_user = user)' – Cole 2013-03-04 19:13:47

+0

您正在討論的過濾器,projects.exclude(added_by_user__iexact = user),我該如何使用它? – holyredbeard 2013-03-04 19:19:10