Detail View Object Related Context

I have 3 model. I try to reach specific context for one them in detail page.

I prepare basic example,
Class Course(models.Model):

Class Restaurant(models.Model):
	rating = models.IntegerField()

Class RestaurantCourse(models.Model): 
	course = models.ForeignKey(Course, on_delete=models.CASCADE)
	restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, related_name="r_courses")
class CourseDetailView(DetailView):
    model = Course
    template_name = 'course-detail.html'

    def get_context_data(self, **kwargs):
        context = super(CourseDetailView, self).get_context_data(**kwargs)
        context['restaurantcourses'] = RestaurantCourse.objects.filter(course = self.object)
        context['related_popular_restaurants'] =  ???
        return context

How can I get related course’s of schools which is rating’s more than 4 ?


So if I can rephrase what you’re looking for, you want all Courses for all Restaurants with rating > 4?
That would be Course.objects.filter(restaurantcourse__restaurant__rating__gt=4)

Thanks for the reply @KenWhitesell.

It’s close but not exactly I need.

In course detail pages, I need restaurants which is related the course and have rating more than 4.

I want to use this context in course-detail.html as,

{% for restaurant in popular_restaurants %}
          {{ }}
          {{ restaurant.image }}
{% endfor %}

At this point, you may want to take some time to review the Making Queries docs, particularly as they relate to foreign key references.

You’re looking to build a list of Restaurant - that’s going to be the base of your query.
So your query is going to start with Restaurant.objects.filter(

You have two conditions that need to be applied, the rating needs to be greater than 4 and it needs to be related to the Course being used in this view (self.object).

  1. When you want to write a query filter where both conditions need to be true, how is that written?
  2. What would the filter be for checking rating being greater than 4?
  3. What would the filter be for checking to see if the related Course is self.object?

For some information related to finding the answer to these questions, see:

  1. Field lookups
  2. Field lookups reference (Yes, it’s a different link)
  3. Related objects

Go ahead and see what you can put together yourself - if you’re still having problems, post what you have tried and we can work forward from there.

Thanks for your detailed answer and guidance.
I will review what you mentioned, I will write the results here.

I have done it. Thanks to @KenWhitesell

context['related_popular_restaurants'] = Restaurant.objects.filter(r_courses__course =self.object, rating__gt=4)

1 Like