django-如何获得团队的所有项目?

问题描述

我是Django的新手,有个问题我自己无法解决。对我来说这是一个大问题。

我想显示与特定团队相关的项目的列表,并在ListView中显示

我认为它应该检查当前用户属于哪个团队,然后根据该团队列出项目。

我的项目中有两个应用程序:1)用户和2)项目

users.models:

from django.contrib.auth.models import AbstractUser 
from django.db import models
from django.contrib.auth import get_user_model 
from django.urls import reverse 


class CustomUser(AbstractUser):
    bio= models.CharField(max_length=300,null= True,blank=True)


class Team (models.Model):

    title = models.CharField(max_length=200)
    user= models.ManyToManyField(get_user_model())
    date_created= models.DateTimeField(auto_Now_add=True,blank=True,null=True)
    date_updated= models.DateTimeField(auto_Now=True,null=True )

    def __str__(self):
        return self.title

    def get_absolute_url(self):  
        return reverse('team_detail',args=[str(self.pk)])


项目模型为

class Project (models.Model):
    team= models.ForeignKey(Team,on_delete=models.CASCADE )
    title = models.CharField(max_length=150,null=False,blank=False)
    notes = models.TextField( null=True,blank=True)
    date_created = models.DateTimeField(auto_Now_add=True,null=True)
    date_updated = models.DateTimeField(auto_Now=True,null=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('project_detail',args=[str(self.pk)])

在projects.views中:我编写了以下代码,但无法计算出两个模型之间的查询集。

class ProjectPageView(ListView):
    model = Project

    def get_queryset(self):
        queryset = super(ProjectPageView,self).get_queryset()
        queryset = queryset.filter( XXXXXXXXXXXXXXX )
        return queryset

    context_object_name = 'projects_list'
    template_name = 'projects/projects.html'

和HTML

{% extends '_base.html' %}

{% block title %}Projects{% endblock title %}

{% block content %}

 <h1> Project list for this Team : </h1>
  {% for project in project_list %}
      <div>
        <h5><a href="{{ project.get_absolute_url }}">{{ project.title }}</a></h5>


      </div>
  {% endfor %}



{% endblock content %}

真的很感谢您的帮助。

解决方法

您可以从请求对象中获取当前用户,然后继续

class ProjectPageView(ListView):
    model = Project

    def get_queryset(self):
        queryset = super(ProjectPageView,self).get_queryset()
        user_team = Team.objects.filter(user=self.request.user).first()
        queryset = queryset.filter(team=user_team)
        return queryset

    context_object_name = 'projects_list'
    template_name = 'projects/projects.html'