根据arg过滤结果

时间:2013-03-04 18:31:07

标签: django filter django-templates filtering

在我的项目管理应用程序中,我有一个列出数据库中所有项目的页面。我希望可以过滤项目,例如,仅显示用户是管理员的项目。下面模板中的代码根据用户点击的内容调用具有不同args的project_list视图。

我需要帮助的是下面视图中的箭头指向的查询,即仅显示用户所属的项目以及用户既不是管理员也不是成员的所有项目。

模板:

<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'和'User'具有多对多关系(即db中存在表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 个答案:

答案 0 :(得分: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.