[Answered ]-How improve this django view code?

2👍

I would start with this small refactoring

from

if request.user.is_authenticated():
    favorite = CarFavorite.objects.filter(user=request.user)
else:
    favorite = []

favorite_user_cars = []
for fav in favorite:
    favorite_user_cars.append(fav.car.id)

to –>

# utils.py 
def _get_favorite_car_ids(user):
    return list(CarFavorite.objects.filter(user=user).values_list('car_id', flat=True)) if user.is_authenticated() else []

# views.py 
favorite_car_ids = _get_favorite_car_ids(request.user)

Leave a comment