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

Time:12-02

I have two models Project and User. A project's team is a many to many field with with the User model.

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)

I am trying to use the Query set API to return the projects a the currently logged on user has been assigned to. However I've been getting the following error:

TypeError: 'User' object is not iterable

How can I resolve this error and get a query set of the projects a user is working on?

CodePudding user response:

Try to change the team property in the Project model to be:

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

Then in the view, you can use

user.user_projects.all()

CodePudding user response:

This line is your culprit:

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

Since it’s a ManyToManyField, you don’t actually have to check __in or even __contains. The records you’re looking for will have the user as the team attribute.

Try this:

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