1

在我的项目管理应用程序中,我有一个页面列出了数据库中的所有项目。我希望可以过滤项目,以便仅显示用户是管理员的项目。下面模板中的代码根据用户单击的内容调用具有不同参数的 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_users 存在于数据库中)。这是项目模型:

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

1 回答 1

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,只需添加一个额外的排除。例如:

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)

过滤器是一个字段查找。django 细节。

于 2013-03-04T18:51:27.807 回答