We have a Django DetailView where we’re displaying an an object (Site), along with all of it’s related objects (Rooms).
Now, in the template, we could simply iterate over the RelatedManager set:
{% for room in site.room_set.all %}
do stuff
{% endfor %}
However, the problem for this is that this will pick up all related rooms to a site – however, we need to narrow this set down somewhat by another attribute (let’s call it year) – and this attribute is stored in a Django session variable.
Currently, we’re just using Room.objects.filter(site=some_site, year='2009') in the view code, and that’s fine.
My question is more from curiosity – is there any way to use _set in the template, and still filter down or narrow the set?
Could you write a custom Model Manager to do this, so that _set will only ever return objects for the current year? Or is there some other way?
Cheers,
Victor
Not by default, since there’s no way to pass arguments to the filter call.
For #3, there are so many factors that determine where this code should go that there’s no general solution. You could import a function into your views? Use a model manager? A model instance method? context processor? etc.
It looks like you can actually just by using a model manager for your reverse related model.
Or just on the parent model: