I am working on a project used to plan stuff in school. How do I implement a site wide filter where I choose department (to work with) and all the list pages showing students only show students, schoolclasses and such relating to this “global departmnet filter”.
Does it even make sense?
I know I can set it somewhere in a form some other place, and use it as a filter option, but I think there must be a better way to limit all the data you want to work with across all views?
If you think about this a little more deeply, you’ll see that it’s not truly “site-wide”.
What I mean by this is that you generally only want this to apply to the standard views, where you have a request object from which you can access the user making the request, and limit their access accordingly.
(The common exceptions to this are either queries that are not executed as part of an http request, such as a Celery task or a custom management command; or the site being worked on in the Django Admin facility.)
Either way, this starts out with the premise that you have a request object with an authenticated user. This means that regardless of what you set up, you’re still going to need to access that user object in order to figure out what needs to be filtered.
You can do this by creating a custom manager with custom querysets Managers | Django documentation | Django, where you pass the current user to that manager. You’ll still need to change your views to use this custom manager with passing either request or request.user as appropriate, so it’s not going to be “invisible” - but it will ensure that the right filters are applied.
So what I get from what you are saying is, that I can save the department choice on the user object and use that in all my queries where I add something like:
Studen.objects.all().filter(department = user.department)
Did I get the right idea?
No, that doesn’t really change anything from what you’re trying to do - you’re still adding your own filter to every query that way.
This does raise a question - are you looking to do this filtering based upon the department of the user who is on the site, or are you having that user select a department to be used on multiple pages? (This doesn’t materially affect what you do, maybe just adjusts some of the specific implementation.)
The option that I am showing is the creating of a custom manager, lets call it “filtered”. You might then create a queryset in “filtered” named department_students.
Your query in your view might then look like: Student.filtered.department_students(request.user)