简体   繁体   English

如何改进此django视图代码?

[英]How improve this django view code?

What do you think about this code part? 您对此代码部分有何看法? How bad it is? 有多糟? It's normal practise to write code like this? 编写这样的代码是正常的做法吗? How I can improve this code and make it shorter, more readable and ofcourse improver performance? 我如何才能改进此代码,使其更短,更易读,从而提高性能?

I think this code isn't very good, especially to understand it and maintain it. 我认为这段代码不是很好,尤其是要理解和维护它。

def car_list(request):

    if request.GET.get('city'):
        city = request.GET.get('city').split(",")[0]
    elif 'city' in request.COOKIES:
        city = request.COOKIES['city'].split(",")[0]
    else:
        city = ''
    not_older_than = request.GET.getlist('not_older_than')
    transmission_type = request.GET.getlist('transmission_type')
    travel_abroad = request.GET.get('travel_abroad')
    insurance = request.GET.get('insurance')
    fuel_type = request.GET.getlist('fuel_type')
    body_type = request.GET.getlist('body_type')
    doors = request.GET.getlist('doors')
    deposit_exists = request.GET.get('deposit_exists')
    delivery_same_city = request.GET.get('delivery_same_city')
    day_run_limit_exists = request.GET.get('day_run_limit_exists')
    seats = request.GET.getlist('seats')

    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)

    q = Q()
    if city:
        q &= Q(city__city=city)
    if not_older_than:
        qx = Q()
        for yr in not_older_than:
            print yr
            year = str(yr)
            print year
            if year == '5':
                qx |= Q(years__gt=int(date.today().year-5))
                print 'yeah yeah 5', int(date.today().year-5)
            if year == '10':
                qx |= Q(years__gt=date.today().year-10, years__lt=date.today().year-5)
                print 'yeah yeah yeah 10'
            if year == '15':
                qx |= Q(years__gt=date.today().year-15, years__lt=date.today().year-10)
            if year == '16':
                qx |= Q(years__lte=date.today().year-15)
        q &=qx
        # q &= Q(city=city)
    if travel_abroad:
        if travel_abroad == u'True':
            q &= Q(travel_abroad=True)
    if insurance:
        q &= Q(insurance=insurance)
    if transmission_type:
        qx = Q()
        for transmission in transmission_type:
            qx |= Q(transmission_type=transmission)
        q &= qx
    if fuel_type:
        qx = Q()
        for fuel in fuel_type:
            qx |= Q(fuel_type=fuel)
        q &= qx
    if body_type:
        qx = Q()
        for body in body_type:
            qx |= Q(body_type=body)
        q &= qx
    if doors:
        qx = Q()
        for door in doors:
            qx |= Q(doors=door)
        q &= qx
    if deposit_exists:
        qx = Q()
        if str(deposit_exists) == 'False':
            qx &= Q(deposit_exists=False)
        q &= qx
    if delivery_same_city:
        if delivery_same_city==u'True':
            q &= Q(do_you_deliver=True)
    if day_run_limit_exists:
        if day_run_limit_exists == u'True':
            q &= Q(day_run_limit_exists=False)
    if seats:
        qx = Q()
        for seat in seats:
            seat = str(seat)
            if seat == '2':
                qx |= Q(seats=2)
            if seat == '4':
                qx |= Q(seats__gte=4, seats__lte=5)
            if seat == '6':
                qx |= Q(seats__gte=6)
        q &= qx 


    if 'filter' in request.GET:
        cars = models.CarForRent.objects.filter(q)
    elif 'body_type' in request.GET:
        body_type = request.GET.get('body_type')
        cars = models.CarForRent.objects.filter(body_type=body_type)
    else:
        cars = models.CarForRent.objects.filter(q)

    car_ratings={}
    rent_prices={}


    if 'end_date' in request.COOKIES:
        total_rent_days = datetime.strptime(request.COOKIES['end_date'], '%Y-%m-%d') -  \
                            datetime.strptime(request.COOKIES['start_date'],'%Y-%m-%d')
        if total_rent_days.days == 0:
            total_rent_days = 1
        else:
            total_rent_days = total_rent_days.days
    else:
        total_rent_days = 1

    for car in cars:
        car_rent_prices = models.CarRentPrice.objects.filter(car=car)
        if car_rent_prices:
            if car_rent_prices.last().end > total_rent_days:
                for price in car_rent_prices:
                    if price.start <= total_rent_days <= price.end:
                        rent_prices[car.id] = total_rent_days * price.price
            else:
                rent_prices[car.id] = total_rent_days * car_rent_prices.last().price

        ratings = UserRating.objects.filter(rating_for=car)
        if len(ratings) > 0:
            service_rating = 0
            car_rating = 0
            how_real_rating = 0

            for rating in ratings:
                service_rating += rating.service
                car_rating += rating.car
                how_real_rating += rating.how_real

            total_rating = round(((service_rating/len(ratings)) + (car_rating/len(ratings)) + \
                (how_real_rating/len(ratings)))/3.0,1)

            car_ratings[car.id] = total_rating
        else:
            car_ratings[car.id] = 0

    sorted_by_price = sorted(rent_prices.items(), key=operator.itemgetter(1))
    sorted_by_rating = sorted(car_ratings.items(), key=operator.itemgetter(1), reverse=True)

    if 'sort_by' in request.GET:
        if request.GET.get('sort_by') == 'price':
            cars = []
            for car_id in sorted_by_price:
                cars.append(models.CarForRent.objects.get(id=car_id[0]))
        elif request.GET.get('sort_by') == 'rating':
            cars = []
            for car_id in sorted_by_rating:
                cars_filter = models.CarForRent.objects.filter(id=car_id[0])
                for car in cars_filter:
                    cars.append(car)
        else:
            cars = []
            for car_id in sorted_by_price:
                cars.append(models.CarForRent.objects.get(id=car_id[0]))
    elif 'sort_param' in request.COOKIES:
        if request.COOKIES['sort_param'] == 'price':
            cars = []
            for car_id in sorted_by_price:
                cars.append(models.CarForRent.objects.get(id=car_id[0]))
        elif request.COOKIES['sort_param'] == 'rating':
            cars = []
            for car_id in sorted_by_rating:
                cars_filter = models.CarForRent.objects.filter(id=car_id[0])
                for car in cars_filter:
                    cars.append(car)
        else:
            cars = []
            for car_id in sorted_by_price:
                # print car_id[0]
                cars.append(models.CarForRent.objects.get(id=car_id[0]))
    else:
        cars = []
        for car_id in sorted_by_price:
            cars.append(models.CarForRent.objects.get(id=car_id[0]))

    paginator = Paginator(cars, 10)

    page = request.GET.get('page')


    try:
        cars = paginator.page(page)
    except PageNotAnInteger:
        cars = paginator.page(1)
    except EmptyPage:
        cars = paginator.page(paginator.num_pages)

    return render(request, 'cars.html', {'city': city, 'cars': cars, 'favorite_user_cars': favorite_user_cars, 'car_ratings': car_ratings, 'rent_prices': rent_prices, 'rent_days': total_rent_days})

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM