import requests import datetime import random from django.conf import settings from django.utils import timezone from django.db.models import F, Q, ExpressionWrapper, fields, Func from django.shortcuts import get_object_or_404 from django.urls import reverse from django.http import Http404 from core.utils import (sql_request_for_api, japan_brands_available, japan_models_available, korea_brands_available, korea_models_available, machinery_brands_available, machinery_models_available, ) from core.models import (TransportBrand, TransportModel, MachineryBrand, MachineryModel, ColorFilter, Rate, MainLot, KoreaLot, MachineryLot, MachineryFilter, MachineryGroup, Review, TransportExperience, MachineryExperience, Video, Article, Question, Category, Banner, Document, StockAuto) from core.enums import (MaxListCars, MaxReviews, MaxTransportExperience, MaxMachineryExperience, MaxVideos, MaxArticles, MaxQuestions, MaxBanners, MaxStockAuto) class Replace(Func): function = 'REPLACE' template = "%(function)s(%(expressions)s, '-', ' ')" class JapanLotsMixin: page_param = 'page' sort_param = 'sort' brand_param = 'brand' model_param = 'model' color_param = 'color' engine_volume_min_param = 'engine_volume_min' engine_volume_max_param = 'engine_volume_max' mileage_min_param = 'mileage_min' mileage_max_param = 'mileage_max' year_min_param = 'year_min' year_max_param = 'year_max' price_min_param = 'price_min' price_max_param = 'price_max' lot_param = 'lot' default_page_param = 1 default_sort_param = 'avg_price' def get_context_data(self, **kwargs): AUCTION_ENDPOINT = settings.AUCTION_ENDPOINT if self.request.ip_address: AUCTION_ENDPOINT = AUCTION_ENDPOINT.replace('?json', f'?json&ip={self.request.ip_address}') context = super().get_context_data(**kwargs) context['curr_title'] = 'Подобрать авто из Японии с доставкой по России - более 42 000 авто на сайте' context[ 'curr_description'] = 'Выберите и закажите авто с аукциона в Японии на нашем сайте. Union Auto возьмет на себя все заботы по приобретению и оптимальной доставке в любой город России. Оставляйте заявку!' # context['canonical'] = reverse('core:catalog_japan') context['page'] = self.request.GET.get(self.page_param, self.default_page_param) context['sort_query'] = self.request.GET.get(self.sort_param, self.default_sort_param) context['brand_query'] = self.request.GET.get(self.brand_param) context['model_query'] = self.request.GET.get(self.model_param) context['color_query'] = self.request.GET.get(self.color_param) context['engine_volume_min_query'] = self.request.GET.get(self.engine_volume_min_param) context['engine_volume_max_query'] = self.request.GET.get(self.engine_volume_max_param) context['mileage_min_query'] = self.request.GET.get(self.mileage_min_param) context['mileage_max_query'] = self.request.GET.get(self.mileage_max_param) context['year_min_query'] = self.request.GET.get(self.year_min_param) context['year_max_query'] = self.request.GET.get(self.year_max_param) context['price_min_query'] = self.request.GET.get(self.price_min_param) context['price_max_query'] = self.request.GET.get(self.price_max_param) context['lot_query'] = self.request.GET.get(self.lot_param) if url_brand := self.kwargs.get('brand'): url_brand = url_brand.replace('-', ' ').upper() url_brand = get_object_or_404(TransportBrand.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_brand) context['brand_query'] = str(url_brand.id) if url_model := self.kwargs.get('model'): url_model = url_model.replace('-', ' ').upper() url_model = get_object_or_404(TransportModel.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_model, category='1', brand=url_brand) context['model_query'] = str(url_model.id) sql_request = f"select * from main where (status LIKE '%25not sold%25' or status='') and (auction not like '%25uss%25') and YEAR>={settings.MIN_YEAR}" if model_id := context['model_query']: model = get_object_or_404(TransportModel, id=model_id, category="1") sql_request += f' and MODEL_ID="{str(model.db_id)}"' sql_request += f' and MARKA_ID="{str(model.brand.db_id)}"' curr_title = f'Выбери свой {model.brand.title} {model.title}' if price_min := self.request.GET.get(self.price_min_param): curr_title += f' по цене от {price_min} ₽' curr_title += ' с аукционов Японии' curr_description = f'Ищете {model.brand.title} {model.title} в хорошем состоянии и адекватной цене? На нашем сайте вы найдете большой выбор автомобилей и спецтехники с аукционов Японии с доставкой по городам РФ.' context['curr_title'] = curr_title context['curr_description'] = curr_description else: if brand_id := context['brand_query']: brand = get_object_or_404(TransportBrand, id=brand_id) sql_request += f' and MARKA_ID="{str(brand.db_id)}"' curr_title = f'Выбери свой {brand.title}' if price_min := self.request.GET.get(self.price_min_param): curr_title += f' по цене от {price_min} ₽' curr_title += ' с аукционов Японии' curr_description = f'Ищете {brand.title} в хорошем состоянии и адекватной цене? На нашем сайте вы найдете большой выбор автомобилей и спецтехники с аукционов Японии с доставкой по городам РФ.' context['curr_title'] = curr_title context['curr_description'] = curr_description if color_id := self.request.GET.get(self.color_param): color = get_object_or_404(ColorFilter, id=color_id) sql_request += f" and COLOR LIKE '%25{color.contain}%25'" if engine_min_volume := self.request.GET.get(self.engine_volume_min_param): try: engine_min_volume = int(engine_min_volume) sql_request += f' and ENG_V>={engine_min_volume}' except: pass if engine_max_volume := self.request.GET.get(self.engine_volume_max_param): try: engine_max_volume = int(engine_max_volume) sql_request += f' and ENG_V<={engine_max_volume}' except: pass if mileage_min := self.request.GET.get(self.mileage_min_param): try: mileage_min = int(mileage_min) sql_request += f' and MILEAGE>={mileage_min}' except: pass if mileage_max := self.request.GET.get(self.mileage_max_param): try: mileage_max = int(mileage_max) sql_request += f' and MILEAGE<={mileage_max}' except: pass if year_min := self.request.GET.get(self.year_min_param): try: year_min = int(year_min) sql_request += f' and YEAR>={year_min}' except: pass if year_max := self.request.GET.get(self.year_max_param): try: year_max = int(year_max) sql_request += f' and YEAR<={year_max}' except: pass if price_min := self.request.GET.get(self.price_min_param): rate = Rate.objects.get(slug='rub-jpy') try: price_min = int(int(price_min) * rate.rate) sql_request += f' and AVG_PRICE>={price_min}' except: pass if price_max := self.request.GET.get(self.price_max_param): rate = Rate.objects.get(slug='rub-jpy') try: price_max = int(int(price_max) * rate.rate) sql_request += f' and AVG_PRICE<={price_max}' except: pass if lot := self.request.GET.get(self.lot_param): sql_request += f' and LOT={lot}' sql_request_quantity = sql_request.replace('*', 'count(*)', 1) sql_request_quantity = sql_request_for_api(sql_request_quantity) try: response = requests.get(AUCTION_ENDPOINT + sql_request_quantity) lots_quantity = int(response.json()[0].get('TAG0')) except: lots_quantity = 0 context['total_lots'] = lots_quantity sort_param = self.request.GET.get(self.sort_param, self.default_sort_param) order_param = '' if '-' in sort_param: order_param = ' desc' sort_param = sort_param.replace('-', '') sql_request += f' order by {sort_param}{order_param}' page_num = int(self.request.GET.get(self.page_param, self.default_page_param)) sql_request += f' limit {(page_num - 1) * MaxListCars.CATALOG_PAGE},{MaxListCars.CATALOG_PAGE}' sql_request = sql_request_for_api(sql_request) try: response = requests.get(AUCTION_ENDPOINT + sql_request) lots = response.json() except: lots = None cars = [] if lots: for lot_info in lots: lot_id = lot_info.get('ID') main_lot, created = MainLot.objects.get_or_create(db_id=lot_id) if created: brand_id = int(lot_info.get('MARKA_ID')) brand_title = lot_info.get('MARKA_NAME').upper() model_id = int(lot_info.get('MODEL_ID')) model_title = lot_info.get('MODEL_NAME').upper() brand, _ = TransportBrand.objects.get_or_create(db_id=brand_id, title=brand_title) model, _ = TransportModel.objects.get_or_create(brand=brand, db_id=model_id, title=model_title, category='1') try: year = int(lot_info.get('YEAR')) except: year = None try: eng_v = int(lot_info.get('ENG_V')) except: eng_v = None try: pw = int(lot_info.get('PW')) except: try: pw = int(lot_info.get('PW').split(',')[0]) except: pw = None try: mileage = int(lot_info.get('MILEAGE')) except: mileage = None try: start = int(lot_info.get('START')) except: start = None try: finish = int(lot_info.get('FINISH')) except: finish = None try: avg_price = int(lot_info.get('AVG_PRICE')) except: avg_price = None images = lot_info.get('IMAGES').split('#') if len(images) > 0: cover = images[0] else: cover = None if len(images) > 1: images = '#'.join(images[1::]) else: images = None main_lot.lot = lot_info.get('LOT') main_lot.auction_date = lot_info.get('AUCTION_DATE') main_lot.auction = lot_info.get('AUCTION') main_lot.car_model = model main_lot.year = year main_lot.eng_v = eng_v main_lot.pw = pw main_lot.town = lot_info.get('TOWN') main_lot.kuzov = lot_info.get('KUZOV') main_lot.grade = lot_info.get('GRADE') main_lot.color = lot_info.get('COLOR') main_lot.kpp = lot_info.get('KPP') main_lot.kpp_type = lot_info.get('KPP_TYPE') main_lot.priv = lot_info.get('PRIV') main_lot.mileage = mileage main_lot.equip = lot_info.get('EQUIP') main_lot.rate = lot_info.get('RATE') main_lot.start = start main_lot.finish = finish main_lot.status = lot_info.get('STATUS') main_lot.time = lot_info.get('TIME') main_lot.avg_price = avg_price main_lot.avg_string = lot_info.get('AVG_STRING') main_lot.cover = cover main_lot.images = images main_lot.save() cars.append(main_lot) context['lots'] = cars if context['brand_query']: models_available = [] if url_brand: models_available = japan_models_available(url_brand.db_id, self.request.ip_address) if models_available: context['models'] = TransportModel.objects.filter(Q(brand__id=context['brand_query']) & Q(category="1") & Q(db_id__in=models_available)).distinct() else: context['models'] = TransportModel.objects.filter( Q(brand__id=context['brand_query']) & Q(category="1")).distinct() return context class KoreanLotsMixin: page_param = 'page' sort_param = 'sort' brand_param = 'brand' model_param = 'model' color_param = 'color' engine_volume_min_param = 'engine_volume_min' engine_volume_max_param = 'engine_volume_max' mileage_min_param = 'mileage_min' mileage_max_param = 'mileage_max' year_min_param = 'year_min' year_max_param = 'year_max' price_min_param = 'price_min' price_max_param = 'price_max' lot_param = 'lot' default_page_param = 1 default_sort_param = 'avg_price' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) AUCTION_ENDPOINT = settings.AUCTION_ENDPOINT if self.request.ip_address: AUCTION_ENDPOINT = AUCTION_ENDPOINT.replace('?json', f'?json&ip={self.request.ip_address}') context['curr_title'] = 'Подобрать авто из Кореи с доставкой по России - более 123 000 авто на сайте' context[ 'curr_description'] = 'Выберите и закажите авто из Кореи на нашем сайте. Union Auto возьмет на себя все заботы по приобретению и оптимальной доставке в любой город России. Оставляйте заявку!' # context['canonical'] = reverse('core:catalog_korea') context['page'] = self.request.GET.get(self.page_param, self.default_page_param) context['sort_query'] = self.request.GET.get(self.sort_param, self.default_sort_param) context['brand_query'] = self.request.GET.get(self.brand_param) context['model_query'] = self.request.GET.get(self.model_param) context['color_query'] = self.request.GET.get(self.color_param) context['engine_volume_min_query'] = self.request.GET.get(self.engine_volume_min_param) context['engine_volume_max_query'] = self.request.GET.get(self.engine_volume_max_param) context['mileage_min_query'] = self.request.GET.get(self.mileage_min_param) context['mileage_max_query'] = self.request.GET.get(self.mileage_max_param) context['year_min_query'] = self.request.GET.get(self.year_min_param) context['year_max_query'] = self.request.GET.get(self.year_max_param) context['price_min_query'] = self.request.GET.get(self.price_min_param) context['price_max_query'] = self.request.GET.get(self.price_max_param) context['lot_query'] = self.request.GET.get(self.lot_param) if url_brand := self.kwargs.get('brand'): url_brand = url_brand.replace('-', ' ').upper() url_brand = get_object_or_404(TransportBrand.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_brand) context['brand_query'] = str(url_brand.id) if url_model := self.kwargs.get('model'): url_model = url_model.replace('-', ' ').upper() url_model = get_object_or_404(TransportModel.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_model, category='2', brand=url_brand) context['model_query'] = str(url_model.id) sql_request = f"select * from korea where (status LIKE '%25not sold%25' or status='') and YEAR>={settings.MIN_YEAR}" if model_id := context['model_query']: model = get_object_or_404(TransportModel, id=model_id, category="2") sql_request += f' and MODEL_ID={model.db_id}' sql_request += f' and MARKA_ID={model.brand.db_id}' curr_title = f'Выбери свой {model.brand.title} {model.title}' if price_min := self.request.GET.get(self.price_min_param): curr_title += f' по цене от {price_min} ₽' curr_title += ' с торговых площадок Кореи' curr_description = f'Ищете {model.brand.title} {model.title} в хорошем состоянии и адекватной цене? На нашем сайте вы найдете большой выбор автомобилей с торговых площадок Кореи с доставкой по городам РФ.' context['curr_title'] = curr_title context['curr_description'] = curr_description else: if brand_id := context['brand_query']: brand = get_object_or_404(TransportBrand, id=brand_id) sql_request += f' and MARKA_ID={brand.db_id}' curr_title = f'Выбери свой {brand.title}' if price_min := self.request.GET.get(self.price_min_param): curr_title += f' по цене от {price_min} ₽' curr_title += ' с торговых площадок Кореи' curr_description = f'Ищете {brand.title} в хорошем состоянии и адекватной цене? На нашем сайте вы найдете большой выбор автомобилей с торговых площадок Кореи с доставкой по городам РФ.' context['curr_title'] = curr_title context['curr_description'] = curr_description if color_id := self.request.GET.get(self.color_param): color = get_object_or_404(ColorFilter, id=color_id) sql_request += f" and COLOR LIKE '%25{color.contain}%25'" if engine_min_volume := self.request.GET.get(self.engine_volume_min_param): try: engine_min_volume = int(engine_min_volume) sql_request += f' and ENG_V>={engine_min_volume}' except: pass if engine_max_volume := self.request.GET.get(self.engine_volume_max_param): try: engine_max_volume = int(engine_max_volume) sql_request += f' and ENG_V<={engine_max_volume}' except: pass if mileage_min := self.request.GET.get(self.mileage_min_param): try: mileage_min = int(mileage_min) sql_request += f' and MILEAGE>={mileage_min}' except: pass if mileage_max := self.request.GET.get(self.mileage_max_param): try: mileage_max = int(mileage_max) sql_request += f' and MILEAGE<={mileage_max}' except: pass if year_min := self.request.GET.get(self.year_min_param): try: year_min = int(year_min) sql_request += f' and YEAR>={year_min}' except: pass if year_max := self.request.GET.get(self.year_max_param): try: year_max = int(year_max) sql_request += f' and YEAR<={year_max}' except: pass if price_min := self.request.GET.get(self.price_min_param): rate = Rate.objects.get(slug='rub-krw') try: price_min = int(int(price_min) * rate.rate) sql_request += f' and AVG_PRICE>={price_min}' except: pass if price_max := self.request.GET.get(self.price_max_param): rate = Rate.objects.get(slug='rub-krw') try: price_max = int(int(price_max) * rate.rate) sql_request += f' and AVG_PRICE<={price_max}' except: pass if lot := self.request.GET.get(self.lot_param): sql_request += f' and LOT={lot}' sql_request_quantity = sql_request.replace('*', 'count(*)', 1) sql_request_quantity = sql_request_for_api(sql_request_quantity) try: response = requests.get(AUCTION_ENDPOINT + sql_request_quantity) lots_quantity = int(response.json()[0].get('TAG0')) except: lots_quantity = 0 context['total_lots'] = lots_quantity sort_param = self.request.GET.get(self.sort_param, self.default_sort_param) order_param = '' if '-' in sort_param: order_param = ' desc' sort_param = sort_param.replace('-', '') sql_request += f' order by {sort_param}{order_param}' page_num = int(self.request.GET.get(self.page_param, self.default_page_param)) sql_request += f' limit {(page_num - 1) * MaxListCars.CATALOG_PAGE},{MaxListCars.CATALOG_PAGE}' sql_request = sql_request_for_api(sql_request) try: response = requests.get(AUCTION_ENDPOINT + sql_request) lots = response.json() except: lots = None if lots: cars = [] for lot_info in lots: lot_id = lot_info.get('ID') main_lot, created = KoreaLot.objects.get_or_create(db_id=lot_id) if created: brand_id = int(lot_info.get('MARKA_ID')) brand_title = lot_info.get('MARKA_NAME').upper() model_id = int(lot_info.get('MODEL_ID')) model_title = lot_info.get('MODEL_NAME').upper() brand, _ = TransportBrand.objects.get_or_create(db_id=brand_id, title=brand_title) model, _ = TransportModel.objects.get_or_create(brand=brand, db_id=model_id, title=model_title, category='2') try: year = int(lot_info.get('YEAR')) except: year = None try: eng_v = int(lot_info.get('ENG_V')) except: eng_v = None try: pw = int(lot_info.get('PW')) except: try: pw = int(lot_info.get('PW').split(',')[0]) except: pw = None try: mileage = int(lot_info.get('MILEAGE')) except: mileage = None try: start = int(lot_info.get('START')) except: start = None try: finish = int(lot_info.get('FINISH')) except: finish = None try: avg_price = int(lot_info.get('AVG_PRICE')) except: avg_price = None images = lot_info.get('IMAGES').split('#') if len(images) > 0: cover = images[0] else: cover = None if len(images) > 1: images = '#'.join(images[1::]) else: images = None main_lot.lot = lot_info.get('LOT') main_lot.auction_date = lot_info.get('AUCTION_DATE') main_lot.auction = lot_info.get('AUCTION') main_lot.car_model = model main_lot.year = year main_lot.eng_v = eng_v main_lot.pw = pw main_lot.kuzov = lot_info.get('KUZOV') main_lot.grade = lot_info.get('GRADE') main_lot.color = lot_info.get('COLOR') main_lot.kpp = lot_info.get('KPP') main_lot.kpp_type = lot_info.get('KPP_TYPE') main_lot.priv = lot_info.get('PRIV') main_lot.mileage = mileage main_lot.equip = lot_info.get('EQUIP') main_lot.rate = lot_info.get('RATE') main_lot.start = start main_lot.finish = finish main_lot.status = lot_info.get('STATUS') main_lot.time = lot_info.get('TIME') main_lot.avg_price = avg_price main_lot.avg_string = lot_info.get('AVG_STRING') main_lot.cover = cover main_lot.images = images main_lot.save() cars.append(main_lot) context['lots'] = cars if context['brand_query']: models_available = [] if url_brand: models_available = korea_models_available(url_brand.db_id, self.request.ip_address) if models_available: context['models'] = TransportModel.objects.filter(Q(brand__id=context['brand_query']) & Q(category="2") & Q(db_id__in=models_available)).distinct() else: context['models'] = TransportModel.objects.filter( Q(brand__id=context['brand_query']) & Q(category="2")).distinct() return context class MachineryLotsMixin: page_param = 'page' sort_param = 'sort' type_param = 'type' brand_param = 'brand' model_param = 'model' price_min_param = 'price_min' price_max_param = 'price_max' lot_param = 'lot' default_page_param = 1 default_sort_param = 'price' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) MACHINERY_ENDPOINT = settings.MACHINERY_ENDPOINT if self.request.ip_address: MACHINERY_ENDPOINT = MACHINERY_ENDPOINT.replace('?json', f'?json&ip={self.request.ip_address}') context['curr_title'] = 'Подобрать спецтехнику из Японии с доставкой по России - более 28 000 единиц на сайте' context[ 'curr_description'] = 'Выберите и закажите спецтехнику с аукциона в Японии на нашем сайте. Union Auto возьмет на себя все заботы по приобретению и оптимальной доставке в любой город России. Оставляйте заявку!' # context['canonical'] = reverse('core:catalog_machinery') context['page'] = self.request.GET.get(self.page_param, self.default_page_param) context['sort_query'] = self.request.GET.get(self.sort_param, self.default_sort_param) context['type_query'] = self.request.GET.get(self.type_param) context['brand_query'] = self.request.GET.get(self.brand_param) context['model_query'] = self.request.GET.get(self.model_param) context['price_min_query'] = self.request.GET.get(self.price_min_param) context['price_max_query'] = self.request.GET.get(self.price_max_param) context['lot_query'] = self.request.GET.get(self.lot_param) if url_brand := self.kwargs.get('brand'): url_brand = url_brand.replace('-', ' ').upper() url_brand = MachineryBrand.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ).filter(clean_title=url_brand).first() if not url_brand: raise Http404("Объект не найден") context['brand_query'] = str(url_brand.id) if url_model := self.kwargs.get('model'): url_model = url_model.replace('-', ' ').upper() url_model = get_object_or_404(MachineryModel.objects.annotate( clean_title=Replace('title') ), clean_title=url_model, brand=url_brand) context['model_query'] = str(url_model.id) sql_request = f"select * from hdm where (status LIKE '%25not sold%25' or status='')" if type_id := self.request.GET.get(self.type_param): machinery_filter = get_object_or_404(MachineryFilter, id=type_id) for num, machinery_group in enumerate(machinery_filter.groups.all()): group_title = machinery_group.title.replace('&', '%26') if num == 0: sql_request += f" and (category LIKE '%25{group_title}%25'" else: sql_request += f" or category LIKE '%25{group_title}%25'" sql_request += ')' if model_id := context['model_query']: model = get_object_or_404(MachineryModel, id=model_id) sql_request += f' and MODEL_NAME LIKE "%25{model.title}%25"' sql_request += f' and MARKA_ID={model.brand.db_id}' curr_title = f'Выбери свой {model.brand.title} {model.title}' if price_min := self.request.GET.get(self.price_min_param): curr_title += f' по цене от {price_min} ₽' curr_title += ' с аукционов Японии' curr_description = f'Ищете {model.brand.title} {model.title} в хорошем состоянии и адекватной цене? На нашем сайте вы найдете большой выбор автомобилей и спецтехники с аукционов Японии с доставкой по городам РФ.' context['curr_title'] = curr_title context['curr_description'] = curr_description else: if brand_id := context['brand_query']: brand = get_object_or_404(MachineryBrand, id=brand_id) sql_request += f' and MARKA_ID={brand.db_id}' curr_title = f'Выбери свой {brand.title}' if price_min := self.request.GET.get(self.price_min_param): curr_title += f' по цене от {price_min} ₽' curr_title += ' с аукционов Японии' curr_description = f'Ищете {brand.title} в хорошем состоянии и адекватной цене? На нашем сайте вы найдете большой выбор автомобилей и спецтехники с аукционов Японии с доставкой по городам РФ.' context['curr_title'] = curr_title context['curr_description'] = curr_description if price_min := self.request.GET.get(self.price_min_param): rate = Rate.objects.get(slug='rub-jpy') try: price_min = int(int(price_min) * rate.rate) sql_request += f' and PRICE>={price_min}' except: pass if price_max := self.request.GET.get(self.price_max_param): rate = Rate.objects.get(slug='rub-jpy') try: price_max = int(int(price_max) * rate.rate) sql_request += f' and PRICE<={price_max}' except: pass if lot := self.request.GET.get(self.lot_param): sql_request += f' and LOT={lot}' sql_request_quantity = sql_request.replace('*', 'count(*)', 1) sql_request_quantity = sql_request_for_api(sql_request_quantity) try: response = requests.get(MACHINERY_ENDPOINT + sql_request_quantity) lots_quantity = int(response.json()[0].get('TAG0')) except: lots_quantity = 0 context['total_lots'] = lots_quantity sort_param = self.request.GET.get(self.sort_param, self.default_sort_param) order_param = '' if '-' in sort_param: order_param = ' desc' sort_param = sort_param.replace('-', '') sql_request += f' order by {sort_param}{order_param}' page_num = int(self.request.GET.get(self.page_param, self.default_page_param)) sql_request += f' limit {(page_num - 1) * MaxListCars.CATALOG_PAGE},{MaxListCars.CATALOG_PAGE}' sql_request = sql_request_for_api(sql_request) try: response = requests.get(MACHINERY_ENDPOINT + sql_request) lots = response.json() except: lots = None if lots: cars = [] for lot_info in lots: lot_id = lot_info.get('ID') main_lot, created = MachineryLot.objects.get_or_create(db_id=lot_id) if created: brand_id = int(lot_info.get('MARKA_ID')) brand_title = lot_info.get('MARKA_NAME').upper() model_title = lot_info.get('MODEL_NAME').upper() brand, _ = MachineryBrand.objects.get_or_create(db_id=brand_id, title=brand_title) model, _ = MachineryModel.objects.get_or_create(brand=brand, title=model_title) try: year = int(lot_info.get('YEAR')) except: year = None try: mileage = int(lot_info.get('MILEAGE')) except: mileage = None try: price = int(lot_info.get('PRICE')) except: price = None try: finish = int(lot_info.get('FINISH')) except: finish = None images = lot_info.get('IMAGES').split('#') if len(images) > 0: cover = images[0] else: cover = None if len(images) > 1: images = '#'.join(images[1::]) else: images = None machinery_group = lot_info.get('CATEGORY') machinery_type = None if machinery_group: curr_group = MachineryGroup.objects.filter(title=machinery_group.upper()).first() if curr_group: machinery_type = curr_group.filters.first() main_lot.lot = lot_info.get('LOT') main_lot.auction_date = lot_info.get('AUCTION_DATE') main_lot.auction = lot_info.get('AUCTION') main_lot.group = lot_info.get('GROUP') main_lot.category = machinery_group main_lot.gg = lot_info.get('GG') main_lot.cc = lot_info.get('CC') main_lot.machinery_model = model main_lot.year = year main_lot.grade = lot_info.get('GRADE') main_lot.kpp = lot_info.get('KPP') main_lot.priv = lot_info.get('PRIV') main_lot.mileage = mileage main_lot.rate = lot_info.get('RATE') main_lot.price = price main_lot.finish = finish main_lot.status = lot_info.get('STATUS') main_lot.cover = cover main_lot.images = images main_lot.machinery_filter = machinery_type main_lot.save() cars.append(main_lot) context['lots'] = cars if context['brand_query']: models_available = [] if url_brand: models_available = machinery_models_available(url_brand.db_id, self.request.ip_address) if models_available: context['models'] = MachineryModel.objects.filter(Q(brand__id=context['brand_query']) & Q(title__in=models_available)).distinct() else: context['models'] = MachineryModel.objects.filter(brand__id=context['brand_query']).distinct() return context class TruckLotsMixin: page_param = 'page' sort_param = 'sort' brand_param = 'brand' model_param = 'model' color_param = 'color' engine_volume_min_param = 'engine_volume_min' engine_volume_max_param = 'engine_volume_max' mileage_min_param = 'mileage_min' mileage_max_param = 'mileage_max' year_min_param = 'year_min' year_max_param = 'year_max' price_min_param = 'price_min' price_max_param = 'price_max' lot_param = 'lot' default_page_param = 1 default_sort_param = 'avg_price' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) AUCTION_ENDPOINT = settings.AUCTION_ENDPOINT if self.request.ip_address: AUCTION_ENDPOINT = AUCTION_ENDPOINT.replace('?json', f'?json&ip={self.request.ip_address}') context['curr_title'] = 'Подобрать грузовой автомобиль из Японии с доставкой по России' context[ 'curr_description'] = 'Выберите и закажите грузовой автомобиль с аукциона в Японии на нашем сайте. Union Auto возьмет на себя все заботы по приобретению и оптимальной доставке в любой город России. Оставляйте заявку!' # context['canonical'] = reverse('core:catalog_japan') context['page'] = self.request.GET.get(self.page_param, self.default_page_param) context['sort_query'] = self.request.GET.get(self.sort_param, self.default_sort_param) context['brand_query'] = self.request.GET.get(self.brand_param) context['model_query'] = self.request.GET.get(self.model_param) context['color_query'] = self.request.GET.get(self.color_param) context['engine_volume_min_query'] = self.request.GET.get(self.engine_volume_min_param) context['engine_volume_max_query'] = self.request.GET.get(self.engine_volume_max_param) context['mileage_min_query'] = self.request.GET.get(self.mileage_min_param) context['mileage_max_query'] = self.request.GET.get(self.mileage_max_param) context['year_min_query'] = self.request.GET.get(self.year_min_param) context['year_max_query'] = self.request.GET.get(self.year_max_param) context['price_min_query'] = self.request.GET.get(self.price_min_param) context['price_max_query'] = self.request.GET.get(self.price_max_param) context['lot_query'] = self.request.GET.get(self.lot_param) if url_brand := self.kwargs.get('brand'): url_brand = url_brand.replace('-', ' ').upper() url_brand = get_object_or_404(TransportBrand.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_brand) context['brand_query'] = str(url_brand.id) if url_model := self.kwargs.get('model'): url_model = url_model.replace('-', ' ').upper() url_model = get_object_or_404(TransportModel.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_model, category='1', brand=url_brand) context['model_query'] = str(url_model.id) sql_request = f"select * from main where (status LIKE '%25not sold%25' or status='') and (auction not like '%25uss%25')" if settings.TRUCKS: sql_request += ' and (' for num, truck in enumerate(settings.TRUCKS): if num == 0: sql_request += f'(MODEL_ID="{str(truck[1])}" and MARKA_ID="{str(truck[0])}")' else: sql_request += f' or (MODEL_ID="{str(truck[1])}" and MARKA_ID="{str(truck[0])}")' sql_request += ')' if model_id := context['model_query']: model = get_object_or_404(TransportModel, id=model_id, category="1") sql_request += f' and MODEL_ID="{str(model.db_id)}"' sql_request += f' and MARKA_ID="{str(model.brand.db_id)}"' curr_title = f'Выбери свой {model.brand.title} {model.title}' if price_min := self.request.GET.get(self.price_min_param): curr_title += f' по цене от {price_min} ₽' curr_title += ' с аукционов Японии' curr_description = f'Ищете {model.brand.title} {model.title} в хорошем состоянии и адекватной цене? На нашем сайте вы найдете большой выбор грузовых автомобилей с аукционов Японии с доставкой по городам РФ.' context['curr_title'] = curr_title context['curr_description'] = curr_description else: if brand_id := context['brand_query']: brand = get_object_or_404(TransportBrand, id=brand_id) sql_request += f' and MARKA_ID="{str(brand.db_id)}"' curr_title = f'Выбери свой {brand.title}' if price_min := self.request.GET.get(self.price_min_param): curr_title += f' по цене от {price_min} ₽' curr_title += ' с аукционов Японии' curr_description = f'Ищете {brand.title} в хорошем состоянии и адекватной цене? На нашем сайте вы найдете большой выбор грузовых автомобилей с аукционов Японии с доставкой по городам РФ.' context['curr_title'] = curr_title context['curr_description'] = curr_description else: sql_request += f' and not MARKA_ID="1"' if color_id := self.request.GET.get(self.color_param): color = get_object_or_404(ColorFilter, id=color_id) sql_request += f" and COLOR LIKE '%25{color.contain}%25'" if engine_min_volume := self.request.GET.get(self.engine_volume_min_param): try: engine_min_volume = int(engine_min_volume) sql_request += f' and ENG_V>={engine_min_volume}' except: pass if engine_max_volume := self.request.GET.get(self.engine_volume_max_param): try: engine_max_volume = int(engine_max_volume) sql_request += f' and ENG_V<={engine_max_volume}' except: pass if mileage_min := self.request.GET.get(self.mileage_min_param): try: mileage_min = int(mileage_min) sql_request += f' and MILEAGE>={mileage_min}' except: pass if mileage_max := self.request.GET.get(self.mileage_max_param): try: mileage_max = int(mileage_max) sql_request += f' and MILEAGE<={mileage_max}' except: pass if year_min := self.request.GET.get(self.year_min_param): try: year_min = int(year_min) sql_request += f' and YEAR>={year_min}' except: pass if year_max := self.request.GET.get(self.year_max_param): try: year_max = int(year_max) sql_request += f' and YEAR<={year_max}' except: pass if price_min := self.request.GET.get(self.price_min_param): rate = Rate.objects.get(slug='rub-jpy') try: price_min = int(int(price_min) * rate.rate) sql_request += f' and AVG_PRICE>={price_min}' except: pass if price_max := self.request.GET.get(self.price_max_param): rate = Rate.objects.get(slug='rub-jpy') try: price_max = int(int(price_max) * rate.rate) sql_request += f' and AVG_PRICE<={price_max}' except: pass if lot := self.request.GET.get(self.lot_param): sql_request += f' and LOT={lot}' sql_request_quantity = sql_request.replace('*', 'count(*)', 1) sql_request_quantity = sql_request_for_api(sql_request_quantity) try: response = requests.get(AUCTION_ENDPOINT + sql_request_quantity) lots_quantity = int(response.json()[0].get('TAG0')) except: lots_quantity = 0 context['total_lots'] = lots_quantity sort_param = self.request.GET.get(self.sort_param, self.default_sort_param) order_param = '' if '-' in sort_param: order_param = ' desc' sort_param = sort_param.replace('-', '') sql_request += f' order by {sort_param}{order_param}' page_num = int(self.request.GET.get(self.page_param, self.default_page_param)) sql_request += f' limit {(page_num - 1) * MaxListCars.CATALOG_PAGE},{MaxListCars.CATALOG_PAGE}' sql_request = sql_request_for_api(sql_request) try: response = requests.get(AUCTION_ENDPOINT + sql_request) lots = response.json() except: lots = None cars = [] if lots: for lot_info in lots: lot_id = lot_info.get('ID') main_lot, created = MainLot.objects.get_or_create(db_id=lot_id) if created: brand_id = int(lot_info.get('MARKA_ID')) brand_title = lot_info.get('MARKA_NAME').upper() model_id = int(lot_info.get('MODEL_ID')) model_title = lot_info.get('MODEL_NAME').upper() brand, _ = TransportBrand.objects.get_or_create(db_id=brand_id, title=brand_title) model, _ = TransportModel.objects.get_or_create(brand=brand, db_id=model_id, title=model_title, category='1') try: year = int(lot_info.get('YEAR')) except: year = None try: eng_v = int(lot_info.get('ENG_V')) except: eng_v = None try: pw = int(lot_info.get('PW')) except: try: pw = int(lot_info.get('PW').split(',')[0]) except: pw = None try: mileage = int(lot_info.get('MILEAGE')) except: mileage = None try: start = int(lot_info.get('START')) except: start = None try: finish = int(lot_info.get('FINISH')) except: finish = None try: avg_price = int(lot_info.get('AVG_PRICE')) except: avg_price = None images = lot_info.get('IMAGES').split('#') if len(images) > 0: cover = images[0] else: cover = None if len(images) > 1: images = '#'.join(images[1::]) else: images = None main_lot.lot = lot_info.get('LOT') main_lot.auction_date = lot_info.get('AUCTION_DATE') main_lot.auction = lot_info.get('AUCTION') main_lot.car_model = model main_lot.year = year main_lot.eng_v = eng_v main_lot.pw = pw main_lot.town = lot_info.get('TOWN') main_lot.kuzov = lot_info.get('KUZOV') main_lot.grade = lot_info.get('GRADE') main_lot.color = lot_info.get('COLOR') main_lot.kpp = lot_info.get('KPP') main_lot.kpp_type = lot_info.get('KPP_TYPE') main_lot.priv = lot_info.get('PRIV') main_lot.mileage = mileage main_lot.equip = lot_info.get('EQUIP') main_lot.rate = lot_info.get('RATE') main_lot.start = start main_lot.finish = finish main_lot.status = lot_info.get('STATUS') main_lot.time = lot_info.get('TIME') main_lot.avg_price = avg_price main_lot.avg_string = lot_info.get('AVG_STRING') main_lot.cover = cover main_lot.images = images main_lot.save() cars.append(main_lot) context['lots'] = cars if context['brand_query']: models_available = [] if url_brand: models_available = japan_models_available(url_brand.db_id, self.request.ip_address) if models_available: context['models'] = TransportModel.objects.filter(Q(brand__id=context['brand_query']) & Q(category="1") & Q(db_id__in=models_available) & Q(db_id__in=settings.TRUCK_MODELS)).distinct() else: context['models'] = TransportModel.objects.filter(Q(brand__id=context['brand_query']) & Q(category="1") & Q(db_id__in=settings.TRUCK_MODELS)).distinct() return context class TitleMixin: title = None def get_context_data(self, **kwargs): context = super(TitleMixin, self).get_context_data() context['title'] = self.title return context class MainPageJapanLotsMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['japan_lots'] = MainLot.objects.filter( Q(full_info=True) & Q(cover__isnull=False) & ~Q(car_model__db_id__in=settings.TRUCK_MODELS)).order_by( '?').distinct()[:MaxListCars.MAIN_PAGE] return context class MainPageKoreanLotsMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['korean_lots'] = KoreaLot.objects.filter(Q(full_info=True) & Q(cover__isnull=False)).order_by( '?').distinct()[:MaxListCars.MAIN_PAGE] return context class MainPageTruckLotsMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['truck_lots'] = MainLot.objects.filter( Q(full_info=True) & Q(cover__isnull=False) & Q(car_model__db_id__in=settings.TRUCK_MODELS) & ~Q(car_model__brand__db_id='1')).order_by('?').distinct()[:MaxListCars.MAIN_PAGE] return context class MainPageMachineryLotsMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['machinery_lots'] = MachineryLot.objects.filter(Q(full_info=True) & Q(cover__isnull=False)).order_by( '?').distinct()[:MaxListCars.MAIN_PAGE] return context class MainPageReviewsMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['reviews'] = Review.objects.filter(Q(is_active=True) & Q(on_main=True)).distinct().select_related( 'screen')[:MaxReviews.MAIN_PAGE] return context class MainPageExperienceMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) experience = [] experience += list( TransportExperience.objects.filter(Q(is_active=True) & Q(on_main=True)).distinct().select_related('cover')[ :MaxTransportExperience.MAIN_PAGE]) experience += list( MachineryExperience.objects.filter(Q(is_active=True) & Q(on_main=True)).distinct().select_related('cover')[ :MaxMachineryExperience.MAIN_PAGE]) context['experience'] = set(experience) return context class MainPageStockAutoMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['stock_auto'] = StockAuto.objects.filter(Q(is_active=True) & Q(on_main=True)).distinct().select_related( 'cover')[:MaxStockAuto.MAIN_PAGE] return context class MainPageVideosMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['videos'] = Video.objects.filter(Q(is_active=True) & Q(on_main=True)).distinct()[:MaxVideos.MAIN_PAGE] return context class MainPageQuestionsMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['questions'] = Question.objects.filter(is_active=True).distinct()[:MaxQuestions.MAIN_PAGE] return context class MainPageArticlesMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['articles'] = Article.objects.filter( Q(is_active=True) & Q(date__lte=timezone.now())).distinct().select_related('cover')[:MaxArticles.MAIN_PAGE] return context class AllLotsMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) lots = [] lots += list(MainLot.objects.filter(Q(full_info=True) & Q(cover__isnull=False)).order_by('?').distinct()[ :MaxListCars.SERVICES_PAGE]) lots += list(KoreaLot.objects.filter(Q(full_info=True) & Q(cover__isnull=False)).order_by('?').distinct()[ :MaxListCars.SERVICES_PAGE]) lots += list(MachineryLot.objects.filter(Q(full_info=True) & Q(cover__isnull=False)).order_by('?').distinct()[ :MaxListCars.MACHINERY_SERVICES_PAGE]) context['lots'] = set(lots) return context class ArticlesSidebarMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['sidebar_articles'] = Article.objects.filter(Q(is_active=True) & Q(date__lte=timezone.now())).order_by( '?').distinct().select_related('cover')[:MaxArticles.SIDEBAR] return context class ReviewsQuerySetMixin: filter_param = 'filter' sort_param = 'sort' default_sort_param = '-date' def get_queryset(self): queryset = super().get_queryset().filter(is_active=True).select_related('screen') filter_query = self.request.GET.get(self.filter_param) if filter_query: queryset = queryset.filter(source=filter_query).distinct() sort_by = self.request.GET.get(self.sort_param, self.default_sort_param) queryset = queryset.order_by(sort_by) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter_query'] = self.request.GET.get(self.filter_param) context['sort_query'] = self.request.GET.get(self.sort_param, self.default_sort_param) return context class ArticlesQuerySetMixin: filter_param = 'filter' def get_queryset(self): queryset = super().get_queryset().filter(Q(is_active=True) & Q(date__lte=timezone.now())).select_related( 'cover') filter_query = self.request.GET.get(self.filter_param) if filter_query: queryset = queryset.filter(category__id=int(filter_query)).distinct() return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter_query'] = self.request.GET.get(self.filter_param) context['categories'] = Category.objects.all() return context class BannersSidebarMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['banners'] = Banner.objects.filter(is_active=True).order_by('?')[:MaxBanners.SIDEBAR] return context class ExperienceAllQuerySetMixin: def get_queryset(self): auto_experience = list(TransportExperience.objects.filter(is_active=True).all()) machinery_experience = list(MachineryExperience.objects.filter(is_active=True).all()) lots = auto_experience + machinery_experience lots.sort(key=lambda obj: obj.id) return lots def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # context['canonical'] = reverse('core:experience_all') context['total_objects'] = len(self.get_queryset()) return context class ExperienceJapanQuerySetMixin: brand_param = 'brand' model_param = 'model' year_min_param = 'year_min' year_max_param = 'year_max' price_min_param = 'price_min' price_max_param = 'price_max' sort_param = 'sort' default_sort_param = 'auction_price_rub' def get_queryset(self): queryset = super().get_queryset().filter(is_active=True).select_related('cover') queryset = queryset.filter(category='1').distinct() brand = self.request.GET.get(self.brand_param) if url_brand := self.kwargs.get('brand'): url_brand = url_brand.replace('-', ' ').upper() url_brand = get_object_or_404(TransportBrand.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_brand) brand = str(url_brand.id) model = self.request.GET.get(self.model_param) if url_model := self.kwargs.get('model'): url_model = url_model.replace('-', ' ').upper() if url_brand: url_model = get_object_or_404(TransportModel.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_model, category='1', brand=url_brand) else: url_model = get_object_or_404(TransportModel.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_model, category='1') model = str(url_model.id) if model: queryset = queryset.filter(transport_model__id=model).distinct() else: if brand: queryset = queryset.filter(brand__id=brand).distinct() min_year = self.request.GET.get(self.year_min_param) if min_year: queryset = queryset.filter(year__gte=int(min_year)).distinct() max_year = self.request.GET.get(self.year_max_param) if max_year: queryset = queryset.filter(year__lte=int(max_year)).distinct() min_price = self.request.GET.get(self.price_min_param) if min_price: queryset = queryset.annotate( total_price=ExpressionWrapper( F('auction_price_rub') + F('delivery_price_rub') + F('tax_price_rub'), output_field=fields.IntegerField() )).filter(total_price__gte=int(min_price)).distinct() max_price = self.request.GET.get(self.price_max_param) if max_price: queryset = queryset.annotate( total_price=ExpressionWrapper( F('auction_price_rub') + F('delivery_price_rub') + F('tax_price_rub'), output_field=fields.IntegerField() )).filter(total_price__lte=int(max_price)).distinct() sort_by = self.request.GET.get(self.sort_param, self.default_sort_param) queryset = queryset.order_by(sort_by) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # context['canonical'] = reverse('core:experience_japan') context['sort_query'] = self.request.GET.get(self.sort_param, self.default_sort_param) context['year_min_query'] = self.request.GET.get(self.year_min_param) context['year_max_query'] = self.request.GET.get(self.year_max_param) context['price_min_query'] = self.request.GET.get(self.price_min_param) context['price_max_query'] = self.request.GET.get(self.price_max_param) context['brand_query'] = self.request.GET.get(self.brand_param) context['model_query'] = self.request.GET.get(self.model_param) if url_brand := self.kwargs.get('brand'): url_brand = url_brand.replace('-', ' ').upper() url_brand = get_object_or_404(TransportBrand.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_brand) context['brand_query'] = str(url_brand.id) if url_model := self.kwargs.get('model'): url_model = url_model.replace('-', ' ').upper() if url_brand: url_model = get_object_or_404(TransportModel.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_model, category='1', brand=url_brand) else: url_model = get_object_or_404(TransportModel.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_model, category='1') context['model_query'] = str(url_model.id) context['brands'] = TransportBrand.objects.filter( Q(transport_experience__isnull=False) & Q(transport_experience__category='1')).distinct() filtered_queryset = self.get_queryset() context['total_objects'] = filtered_queryset.count() if context['brand_query']: context['models'] = TransportModel.objects.filter(Q(transport_experience__isnull=False) & Q(transport_experience__category='1') & Q(transport_experience__brand__id=context[ 'brand_query']) & Q(category='1')).distinct() return context class ExperienceKoreaQuerySetMixin: brand_param = 'brand' model_param = 'model' year_min_param = 'year_min' year_max_param = 'year_max' price_min_param = 'price_min' price_max_param = 'price_max' sort_param = 'sort' default_sort_param = 'auction_price_rub' def get_queryset(self): queryset = super().get_queryset().filter(is_active=True).select_related('cover') queryset = queryset.filter(category='2').distinct() model = self.request.GET.get(self.model_param) if url_model := self.kwargs.get('model'): url_model = url_model.replace('-', ' ').upper() url_model = get_object_or_404(TransportModel.objects.annotate( clean_title=Replace('title') ), clean_title=url_model, category='2') model = str(url_model.id) if model: queryset = queryset.filter(transport_model__id=model).distinct() else: brand = self.request.GET.get(self.brand_param) if url_brand := self.kwargs.get('brand'): url_brand = url_brand.replace('-', ' ').upper() url_brand = get_object_or_404(TransportBrand.objects.annotate( clean_title=Replace('title') ), clean_title=url_brand) brand = str(url_brand.id) if brand: queryset = queryset.filter(brand__id=brand).distinct() min_year = self.request.GET.get(self.year_min_param) if min_year: queryset = queryset.filter(year__gte=int(min_year)).distinct() max_year = self.request.GET.get(self.year_max_param) if max_year: queryset = queryset.filter(year__lte=int(max_year)).distinct() min_price = self.request.GET.get(self.price_min_param) if min_price: queryset = queryset.annotate( total_price=ExpressionWrapper( F('auction_price_rub') + F('delivery_price_rub') + F('tax_price_rub'), output_field=fields.IntegerField() )).filter(total_price__gte=int(min_price)).distinct() max_price = self.request.GET.get(self.price_max_param) if max_price: queryset = queryset.annotate( total_price=ExpressionWrapper( F('auction_price_rub') + F('delivery_price_rub') + F('tax_price_rub'), output_field=fields.IntegerField() )).filter(total_price__lte=int(max_price)).distinct() sort_by = self.request.GET.get(self.sort_param, self.default_sort_param) queryset = queryset.order_by(sort_by) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # context['canonical'] = reverse('core:experience_korea') context['sort_query'] = self.request.GET.get(self.sort_param, self.default_sort_param) context['year_min_query'] = self.request.GET.get(self.year_min_param) context['year_max_query'] = self.request.GET.get(self.year_max_param) context['price_min_query'] = self.request.GET.get(self.price_min_param) context['price_max_query'] = self.request.GET.get(self.price_max_param) context['brand_query'] = self.request.GET.get(self.brand_param) context['model_query'] = self.request.GET.get(self.model_param) context['brands'] = TransportBrand.objects.filter( Q(transport_experience__isnull=False) & Q(transport_experience__category='2')).distinct() if url_brand := self.kwargs.get('brand'): url_brand = url_brand.replace('-', ' ').upper() url_brand = get_object_or_404(TransportBrand.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_brand) context['brand_query'] = str(url_brand.id) if url_model := self.kwargs.get('model'): url_model = url_model.replace('-', ' ').upper() url_model = get_object_or_404(TransportModel.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_model, category='2', brand=url_brand) context['model_query'] = str(url_model.id) filtered_queryset = self.get_queryset() context['total_objects'] = filtered_queryset.count() if context['brand_query']: context['models'] = TransportModel.objects.filter(Q(transport_experience__isnull=False) & Q(transport_experience__category='2') & Q(transport_experience__brand__id=context[ 'brand_query']) & Q(category='2')).distinct() return context class ExperienceMachineryQuerySetMixin: brand_param = 'brand' model_param = 'model' year_min_param = 'year_min' year_max_param = 'year_max' price_min_param = 'price_min' price_max_param = 'price_max' sort_param = 'sort' default_sort_param = 'auction_price_rub' def get_queryset(self): queryset = super().get_queryset().filter(is_active=True).select_related('cover') model = self.request.GET.get(self.model_param) if url_model := self.kwargs.get('model'): url_model = url_model.replace('-', ' ').upper() url_model = get_object_or_404(MachineryModel.objects.annotate( clean_title=Replace('title') ), clean_title=url_model) model = str(url_model.id) if model: queryset = queryset.filter(transport_model__id=model).distinct() else: brand = self.request.GET.get(self.brand_param) if url_brand := self.kwargs.get('brand'): url_brand = url_brand.replace('-', ' ').upper() url_brand = MachineryBrand.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ).filter(clean_title=url_brand).first() if not url_brand: raise Http404("Объект не найден") brand = str(url_brand.id) if brand: queryset = queryset.filter(brand__id=brand).distinct() min_year = self.request.GET.get(self.year_min_param) if min_year: queryset = queryset.filter(year__gte=int(min_year)).distinct() max_year = self.request.GET.get(self.year_max_param) if max_year: queryset = queryset.filter(year__lte=int(max_year)).distinct() min_price = self.request.GET.get(self.price_min_param) if min_price: queryset = queryset.annotate( total_price=ExpressionWrapper( F('auction_price_rub') + F('delivery_price_rub') + F('tax_price_rub'), output_field=fields.IntegerField() )).filter(total_price__gte=int(min_price)).distinct() max_price = self.request.GET.get(self.price_max_param) if max_price: queryset = queryset.annotate( total_price=ExpressionWrapper( F('auction_price_rub') + F('delivery_price_rub') + F('tax_price_rub'), output_field=fields.IntegerField() )).filter(total_price__lte=int(max_price)).distinct() sort_by = self.request.GET.get(self.sort_param, self.default_sort_param) queryset = queryset.order_by(sort_by) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # context['canonical'] = reverse('core:experience_machinery') context['sort_query'] = self.request.GET.get(self.sort_param, self.default_sort_param) context['year_min_query'] = self.request.GET.get(self.year_min_param) context['year_max_query'] = self.request.GET.get(self.year_max_param) context['price_min_query'] = self.request.GET.get(self.price_min_param) context['price_max_query'] = self.request.GET.get(self.price_max_param) context['brand_query'] = self.request.GET.get(self.brand_param) context['model_query'] = self.request.GET.get(self.model_param) context['brands'] = MachineryBrand.objects.filter( Q(transport_experience__isnull=False) & ~Q(db_id='0')).distinct() if url_brand := self.kwargs.get('brand'): url_brand = url_brand.replace('-', ' ').upper() url_brand = MachineryBrand.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ).filter(clean_title=url_brand).first() if not url_brand: raise Http404("Объект не найден") context['brand_query'] = str(url_brand.id) if url_model := self.kwargs.get('model'): url_model = url_model.replace('-', ' ').upper() url_model = get_object_or_404(MachineryModel.objects.annotate( clean_title=Replace('title') ), clean_title=url_model, brand=url_brand) context['model_query'] = str(url_model.id) filtered_queryset = self.get_queryset() context['total_objects'] = filtered_queryset.count() if context['brand_query']: context['models'] = MachineryModel.objects.filter(Q(transport_experience__isnull=False) & Q(transport_experience__brand__id=context[ 'brand_query'])).distinct() return context class DocumentsMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['documents'] = Document.objects.all() return context class JapanBrandsMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) brands = japan_brands_available(self.request.ip_address) if brands: context['brands'] = TransportBrand.objects.filter(Q(transport_models__category='1') & Q(db_id__in=brands)).distinct() else: context['brands'] = TransportBrand.objects.filter(transport_models__category='1').distinct() return context class TruckBrandsMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) brands = japan_brands_available(self.request.ip_address, True) if brands: context['brands'] = TransportBrand.objects.filter(Q(transport_models__category='1') & Q(db_id__in=brands) & Q(db_id__in=settings.TRUCK_BRANDS)).distinct() else: context['brands'] = TransportBrand.objects.filter(Q(transport_models__category='1') & Q(db_id__in=settings.TRUCK_BRANDS)).distinct() return context class KoreaBrandsMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) brands = korea_brands_available(self.request.ip_address) if brands: context['brands'] = TransportBrand.objects.filter(Q(transport_models__category='2') & Q(db_id__in=brands)).distinct() else: context['brands'] = TransportBrand.objects.filter(transport_models__category='2').distinct() return context class MachineryBrandsMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) brands = machinery_brands_available(self.request.ip_address) if brands: context['brands'] = MachineryBrand.objects.filter(Q(db_id__in=brands) & ~Q(db_id='0')).all() else: context['brands'] = MachineryBrand.objects.filter(~Q(db_id='0')).all() return context class ColorMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['colors'] = ColorFilter.objects.all() return context class MachineryFilterMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['types'] = MachineryFilter.objects.all() return context class MainBrandsMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) brands = settings.MAIN_PAGE_JAPAN_BRANDS + settings.MAIN_PAGE_KOREA_BRANDS main_brands = {} for brand in brands: curr_brand = TransportBrand.objects.filter(title=brand).first() if curr_brand: brand = brand.replace(' ', '_') main_brands[brand] = curr_brand.id context['main_brands'] = main_brands return context class MainMachineryFiltersMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['machinery_filters'] = MachineryFilter.objects.filter(on_main=True, icon__isnull=False).all() return context class AllCatalogLotsMixin: page_param = 'page' default_page_param = 1 def get_context_data(self, **kwargs): AUCTION_ENDPOINT = settings.AUCTION_ENDPOINT if self.request.ip_address: AUCTION_ENDPOINT = AUCTION_ENDPOINT.replace('?json', f'?json&ip={self.request.ip_address}') MACHINERY_ENDPOINT = settings.MACHINERY_ENDPOINT if self.request.ip_address: MACHINERY_ENDPOINT = MACHINERY_ENDPOINT.replace('?json', f'?json&ip={self.request.ip_address}') context = super().get_context_data(**kwargs) context['page'] = self.request.GET.get(self.page_param, self.default_page_param) total_lots_quantity = 0 sql_request = f"select * from main where (status LIKE '%25not sold%25' or status='') and (auction not like '%25uss%25') and YEAR>={settings.MIN_YEAR}" sql_request_quantity = sql_request.replace('*', 'count(*)', 1) sql_request_quantity = sql_request_for_api(sql_request_quantity) try: response = requests.get(AUCTION_ENDPOINT + sql_request_quantity) lots_quantity = int(response.json()[0].get('TAG0')) except: lots_quantity = 0 total_lots_quantity += lots_quantity page_num = int(self.request.GET.get(self.page_param, self.default_page_param)) sql_request += f' limit {(page_num - 1) * MaxListCars.AUTO_ALL_CATALOG},{MaxListCars.AUTO_ALL_CATALOG}' sql_request = sql_request_for_api(sql_request) try: response = requests.get(AUCTION_ENDPOINT + sql_request) lots = response.json() except: lots = None cars = [] if lots: for lot_info in lots: lot_id = lot_info.get('ID') main_lot, created = MainLot.objects.get_or_create(db_id=lot_id) if created: brand_id = int(lot_info.get('MARKA_ID')) brand_title = lot_info.get('MARKA_NAME').upper() model_id = int(lot_info.get('MODEL_ID')) model_title = lot_info.get('MODEL_NAME').upper() brand, _ = TransportBrand.objects.get_or_create(db_id=brand_id, title=brand_title) model, _ = TransportModel.objects.get_or_create(brand=brand, db_id=model_id, title=model_title, category='1') try: year = int(lot_info.get('YEAR')) except: year = None try: eng_v = int(lot_info.get('ENG_V')) except: eng_v = None try: pw = int(lot_info.get('PW')) except: try: pw = int(lot_info.get('PW').split(',')[0]) except: pw = None try: mileage = int(lot_info.get('MILEAGE')) except: mileage = None try: start = int(lot_info.get('START')) except: start = None try: finish = int(lot_info.get('FINISH')) except: finish = None try: avg_price = int(lot_info.get('AVG_PRICE')) except: avg_price = None images = lot_info.get('IMAGES').split('#') if len(images) > 0: cover = images[0] else: cover = None if len(images) > 1: images = '#'.join(images[1::]) else: images = None main_lot.lot = lot_info.get('LOT') main_lot.auction_date = lot_info.get('AUCTION_DATE') main_lot.auction = lot_info.get('AUCTION') main_lot.car_model = model main_lot.year = year main_lot.eng_v = eng_v main_lot.pw = pw main_lot.town = lot_info.get('TOWN') main_lot.kuzov = lot_info.get('KUZOV') main_lot.grade = lot_info.get('GRADE') main_lot.color = lot_info.get('COLOR') main_lot.kpp = lot_info.get('KPP') main_lot.kpp_type = lot_info.get('KPP_TYPE') main_lot.priv = lot_info.get('PRIV') main_lot.mileage = mileage main_lot.equip = lot_info.get('EQUIP') main_lot.rate = lot_info.get('RATE') main_lot.start = start main_lot.finish = finish main_lot.status = lot_info.get('STATUS') main_lot.time = lot_info.get('TIME') main_lot.avg_price = avg_price main_lot.avg_string = lot_info.get('AVG_STRING') main_lot.cover = cover main_lot.images = images main_lot.save() cars.append(main_lot) sql_request = f"select * from korea where (status LIKE '%25not sold%25' or status='') and YEAR>={settings.MIN_YEAR}" sql_request_quantity = sql_request.replace('*', 'count(*)', 1) sql_request_quantity = sql_request_for_api(sql_request_quantity) try: response = requests.get(settings.AUCTION_ENDPOINT + sql_request_quantity) lots_quantity = int(response.json()[0].get('TAG0')) except: lots_quantity = 0 total_lots_quantity += lots_quantity page_num = int(self.request.GET.get(self.page_param, self.default_page_param)) sql_request += f' limit {(page_num - 1) * MaxListCars.AUTO_ALL_CATALOG},{MaxListCars.AUTO_ALL_CATALOG}' sql_request = sql_request_for_api(sql_request) try: response = requests.get(AUCTION_ENDPOINT + sql_request) lots = response.json() except: lots = None if lots: for lot_info in lots: lot_id = lot_info.get('ID') main_lot, created = KoreaLot.objects.get_or_create(db_id=lot_id) if created: brand_id = int(lot_info.get('MARKA_ID')) brand_title = lot_info.get('MARKA_NAME').upper() model_id = int(lot_info.get('MODEL_ID')) model_title = lot_info.get('MODEL_NAME').upper() brand, _ = TransportBrand.objects.get_or_create(db_id=brand_id, title=brand_title) model, _ = TransportModel.objects.get_or_create(brand=brand, db_id=model_id, title=model_title, category='2') try: year = int(lot_info.get('YEAR')) except: year = None try: eng_v = int(lot_info.get('ENG_V')) except: eng_v = None try: pw = int(lot_info.get('PW')) except: try: pw = int(lot_info.get('PW').split(',')[0]) except: pw = None try: mileage = int(lot_info.get('MILEAGE')) except: mileage = None try: start = int(lot_info.get('START')) except: start = None try: finish = int(lot_info.get('FINISH')) except: finish = None try: avg_price = int(lot_info.get('AVG_PRICE')) except: avg_price = None images = lot_info.get('IMAGES').split('#') if len(images) > 0: cover = images[0] else: cover = None if len(images) > 1: images = '#'.join(images[1::]) else: images = None main_lot.lot = lot_info.get('LOT') main_lot.auction_date = lot_info.get('AUCTION_DATE') main_lot.auction = lot_info.get('AUCTION') main_lot.car_model = model main_lot.year = year main_lot.eng_v = eng_v main_lot.pw = pw main_lot.kuzov = lot_info.get('KUZOV') main_lot.grade = lot_info.get('GRADE') main_lot.color = lot_info.get('COLOR') main_lot.kpp = lot_info.get('KPP') main_lot.kpp_type = lot_info.get('KPP_TYPE') main_lot.priv = lot_info.get('PRIV') main_lot.mileage = mileage main_lot.equip = lot_info.get('EQUIP') main_lot.rate = lot_info.get('RATE') main_lot.start = start main_lot.finish = finish main_lot.status = lot_info.get('STATUS') main_lot.time = lot_info.get('TIME') main_lot.avg_price = avg_price main_lot.avg_string = lot_info.get('AVG_STRING') main_lot.cover = cover main_lot.images = images main_lot.save() cars.append(main_lot) sql_request = f"select * from hdm where (status LIKE '%25not sold%25' or status='')" sql_request_quantity = sql_request.replace('*', 'count(*)', 1) sql_request_quantity = sql_request_for_api(sql_request_quantity) try: response = requests.get(MACHINERY_ENDPOINT + sql_request_quantity) lots_quantity = int(response.json()[0].get('TAG0')) except: lots_quantity = 0 total_lots_quantity += lots_quantity page_num = int(self.request.GET.get(self.page_param, self.default_page_param)) sql_request += f' limit {(page_num - 1) * MaxListCars.MACHINERY_ALL_CATALOG},{MaxListCars.MACHINERY_ALL_CATALOG}' sql_request = sql_request_for_api(sql_request) try: response = requests.get(MACHINERY_ENDPOINT + sql_request) lots = response.json() except: lots = None if lots: for lot_info in lots: lot_id = lot_info.get('ID') main_lot, created = MachineryLot.objects.get_or_create(db_id=lot_id) if created: brand_id = int(lot_info.get('MARKA_ID')) brand_title = lot_info.get('MARKA_NAME').upper() model_title = lot_info.get('MODEL_NAME').upper() brand, _ = MachineryBrand.objects.get_or_create(db_id=brand_id, title=brand_title) model, _ = MachineryModel.objects.get_or_create(brand=brand, title=model_title) try: year = int(lot_info.get('YEAR')) except: year = None try: mileage = int(lot_info.get('MILEAGE')) except: mileage = None try: price = int(lot_info.get('PRICE')) except: price = None try: finish = int(lot_info.get('FINISH')) except: finish = None images = lot_info.get('IMAGES').split('#') if len(images) > 0: cover = images[0] else: cover = None if len(images) > 1: images = '#'.join(images[1::]) else: images = None machinery_group = lot_info.get('CATEGORY') machinery_type = None if machinery_group: curr_group = MachineryGroup.objects.filter(title=machinery_group.upper()).first() if curr_group: machinery_type = curr_group.filters.first() main_lot.lot = lot_info.get('LOT') main_lot.auction_date = lot_info.get('AUCTION_DATE') main_lot.auction = lot_info.get('AUCTION') main_lot.group = lot_info.get('GROUP') main_lot.category = machinery_group main_lot.gg = lot_info.get('GG') main_lot.cc = lot_info.get('CC') main_lot.machinery_model = model main_lot.year = year main_lot.grade = lot_info.get('GRADE') main_lot.kpp = lot_info.get('KPP') main_lot.priv = lot_info.get('PRIV') main_lot.mileage = mileage main_lot.rate = lot_info.get('RATE') main_lot.price = price main_lot.finish = finish main_lot.status = lot_info.get('STATUS') main_lot.cover = cover main_lot.images = images main_lot.machinery_filter = machinery_type main_lot.save() cars.append(main_lot) random.shuffle(cars) context['lots'] = cars context['total_lots'] = total_lots_quantity # context['canonical'] = reverse('core:catalog_all') return context class StockAutoQuerySetMixin: brand_param = 'brand' model_param = 'model' city_param = 'city' year_min_param = 'year_min' year_max_param = 'year_max' price_min_param = 'price_min' price_max_param = 'price_max' engine_param = 'engine' import_param = 'import' sort_param = 'sort' default_sort_param = 'price' def get_queryset(self): queryset = super().get_queryset().filter(is_active=True).select_related('cover') brand = self.request.GET.get(self.brand_param) if url_brand := self.kwargs.get('brand'): url_brand = url_brand.replace('-', ' ').upper() url_brand = get_object_or_404(TransportBrand.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_brand) brand = str(url_brand.id) model = self.request.GET.get(self.model_param) if url_model := self.kwargs.get('model'): url_category = url_model[-1] if url_category == '0': url_category = '1' url_model = url_model[:-2] url_model = url_model.replace('-', ' ').upper() if url_brand: url_model = get_object_or_404(TransportModel.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_model, category=url_category, brand=url_brand) else: url_model = get_object_or_404(TransportModel.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_model, category=url_category) model = str(url_model.id) if model: queryset = queryset.filter(transport_model__id=model).distinct() else: if brand: queryset = queryset.filter(brand__id=brand).distinct() city = self.request.GET.get(self.city_param) if city: queryset = queryset.filter(city__isnull=False, city__slug=city).distinct() engine = self.request.GET.get(self.engine_param) if engine: queryset = queryset.filter(engine__isnull=False, engine__slug=engine).distinct() import_type = self.request.GET.get(self.import_param) if import_type: queryset = queryset.filter(import_type__isnull=False, import_type__slug=import_type).distinct() min_year = self.request.GET.get(self.year_min_param) if min_year: queryset = queryset.filter(year__gte=int(min_year)).distinct() max_year = self.request.GET.get(self.year_max_param) if max_year: queryset = queryset.filter(year__lte=int(max_year)).distinct() min_price = self.request.GET.get(self.price_min_param) if min_price: queryset = queryset.filter(price=int(min_price)).distinct() max_price = self.request.GET.get(self.price_max_param) if max_price: queryset = queryset.filter(price__lte=int(max_price)).distinct() sort_by = self.request.GET.get(self.sort_param, self.default_sort_param) queryset = queryset.order_by(sort_by) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # context['canonical'] = reverse('core:experience_japan') context['sort_query'] = self.request.GET.get(self.sort_param, self.default_sort_param) context['year_min_query'] = self.request.GET.get(self.year_min_param) context['year_max_query'] = self.request.GET.get(self.year_max_param) context['price_min_query'] = self.request.GET.get(self.price_min_param) context['price_max_query'] = self.request.GET.get(self.price_max_param) context['brand_query'] = self.request.GET.get(self.brand_param) context['model_query'] = self.request.GET.get(self.model_param) context['city_query'] = self.request.GET.get(self.city_param) context['engine_query'] = self.request.GET.get(self.engine_param) context['import_query'] = self.request.GET.get(self.import_param) if url_brand := self.kwargs.get('brand'): url_brand = url_brand.replace('-', ' ').upper() url_brand = get_object_or_404(TransportBrand.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_brand) context['brand_query'] = str(url_brand.id) if url_model := self.kwargs.get('model'): url_category = url_model[-1] if url_category == '0': url_category = '1' url_model = url_model[:-2] url_model = url_model.replace('-', ' ').upper() if url_brand: url_model = get_object_or_404(TransportModel.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_model, category=url_category, brand=url_brand) else: url_model = get_object_or_404(TransportModel.objects.filter(~Q(db_id="0")).annotate( clean_title=Replace('title') ), clean_title=url_model, category=url_category) context['model_query'] = str(url_model.id) context['brands'] = TransportBrand.objects.filter(autos_in_stock__isnull=False).distinct() filtered_queryset = self.get_queryset() context['total_objects'] = filtered_queryset.count() if context['brand_query']: context['models'] = TransportModel.objects.filter(Q(autos_in_stock__isnull=False) & Q(autos_in_stock__brand__id=context['brand_query']) ).distinct() return context class YearsMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) curr_year = datetime.datetime.utcnow().year context['years'] = range(settings.MIN_YEAR, curr_year + 1) return context