根据用户是否属于项目团队进行过滤

Filter based on whether a user is part of a project's team

我有两个模型项目和用户。一个项目的团队是一个多对多的字段,使用用户模型。

models.py

# Create your models here.
class Project(models.Model):
    title = CharField(max_length=30)
    description = TextField()
    due_date = DateField()
    team = ManyToManyField(settings.AUTH_USER_MODEL)
    INACTIVE = 0
    ACTIVE = 1
    STATUS = (
        (INACTIVE, ('Inactive')),
        (ACTIVE, ('Active')),
    )

    active  = models.IntegerField(default=1, choices=STATUS)

    def __str__(self) -> str:
        return f'{self.title}'

views.py

@login_required
def index(request):
    user = request.user
    tickets = Ticket.objects.filter(assigned_to=user)
    ticket_count = len(tickets)
    projects = Project.objects.filter(team__in = user)
    project_count = len(projects)
    context = {
        'tickets':tickets,
        'ticket_count':ticket_count,
        'projects':projects,
        'project_count':project_count,
    }
    return render(request, 'bugtracker_app/index.html', context)

我正在尝试使用查询集 API 到 return 当前登录用户已分配到的项目。但是我一直收到以下错误:

TypeError: 'User' object is not iterable

如何解决此错误并获取用户正在处理的项目的查询集?

尝试将项目模型中的团队 属性 更改为:

team = ManyToManyField(settings.AUTH_USER_MODEL, related_name= 'user_projects')

然后在视图中,可以使用

user.user_projects.all()

这一行是你的罪魁祸首:

projects = Project.objects.filter(team__in = user)

因为它是一个 ManyToManyField,你实际上不必检查 __in 甚至 __contains。您要查找的记录会将用户作为团队属性。

试试这个:

projects = Project.objects.filter(team = user)