Create view that shows all objects relating to current user's department

I have the following Django model:

from django.conf import settings
from django.db import models

class Appeal(models.Model):

        ("a", "DeptA"),
        ("b", "DeptB"),
        ("c", "DeptC"),
        # long list of departments here

    title = models.CharField(max_length=400)
    department = models.CharField(choices=DEPARTMENTS)
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="appeals"

And a view like this:

from django.shortcuts import get_list_or_404, render

def appeal_list_view(request):
    visible_appeals = get_list_or_404(Appeal, author=request.user)
    return render(request, "appeals/index.html", {"appeals": visible_appeals})

This shows only the appeals by the current user. I would like to change this code so that:

  • each user is associated with a department,
  • a user is shown all appeals from their own department (regardless of whether or not they or another user from the same department submitted it).

What would be the best way to achieve this? I considered creating a group per department, which would solve the first requirement but then I’m not sure how to approach the second one.

>Solution :

You can use Lookups that span relationships

Assuming that your user model has a field named department that represents user’s department.. you can update your query to something like:

visible_appeals = get_list_or_404(Appeal, author__department=request.user.department)

Leave a Reply