Search code examples
djangodjango-modelsdjango-templatesdjango-1.8

Django 1.8 How to filter an object by id of current generic Detail View


I am struggling (due to being new to django) with how to filter an object by the current details views ID.

For example, I am writing a test app that allows "venues" to have their own detail page and on that page they can display their "Menu" items, "OpeningHours" etc.

Here is what I am sending from the view to the template:

class DetailView(generic.DetailView):
    model = Venue
    template_name = 'nmq/detail.html'

    def get_queryset(self):
        return Venue.objects.all()

    def get_context_data(self, **kwargs):
        context = super(DetailView, self).get_context_data(**kwargs)
        context['OpeningHours'] = OpeningHours.objects.all()
        context['Menu'] = Menu.objects.all()
        context['Venue'] = self.queryset
        return context

I can easily manage to get all OpeningHours from that model but this is shared across all users. I am trying to filter this by the id of the current page. I can access this on the detail page by using {{ venue.id }} but I cannot seem to manage to pull this together with anything else to just get menu items of opening hours for that particular id.


Solution

  • Inside the get_context_data method for the detail view, you can access the object with self.object. Therefore you can filter with something like:

    def get_context_data(self, **kwargs):
        context = super(DetailView, self).get_context_data(**kwargs)
        context['OpeningHours'] = OpeningHours.objects.filter(venue=self.object)
        context['Menu'] = Menu.objects.filter(self.object)
        return context
    

    I don't think you need to set context['Venue'] = self.queryset. The DetailView allows you to access the venue with {{ object }} or {{ venue }} in the template.