get_object_or_404 with values
django, python
Solution
You can pass a queryset as the first parameter, instead of a model class. Here you can use `select_related` (and `prefetch_related`, but it seems you need the first one) to reduce database queries:
def car(request, car_id):
cars = Car.objects.select_related('options')
car = get_object_or_404(cars, pk=car_id, active=1)
return render(request, 'car.html', {'car': car})
Problem
views.py: ``` def car(request, car_id): car = get_object_or_404(Car, pk=car_id, active=1) return render(request, 'car.html', {'car': car,} ) ``` in car.html: ``` ... {{ car.mark }}, {{ car.options.year }}, etc. ... ``` So, I have many requests to my db. In another view I use ``` all_cars = Cars.objects.all().filter(active=1).values(...) ``` And in this variant I have only 2 request to db. Yes, I know, that I can use in car`s view: ``` car = Car.objects.filter(id=car_id, active=1).values(...)[0] ``` Is any other variants to do the same with get_object_or_404 or something, that not doing many requests to db? Thanks!