Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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):

    DEPARTMENTS = [
        ("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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading