def grow_position(request):
form = PositionForm(request.GET)
if form.is_valid():
last_year = form.cleaned_data['last_year'] * 1000000
year_before_last = form.cleaned_data['year_before_last'] * 1000000
growth = calc_growth(last_year, year_before_last)
if growth <= 0:
return JsonResponse({'text': gettext('У вас отрицательный рост, вы не можете участвовать в рейтинге')})
companies = get_companies_info()
if not companies:
return JsonResponse({'text': gettext('Невозможно определить рейтинг')})
median = companies[0][1]['median']
score = calc_score(last_year, growth, median)
for number, (company, info) in enumerate(companies, start=1):
if score > info['score']:
return JsonResponse({'text': gettext(f'Ваша позиция в рейтинге {number}')})
return JsonResponse({'text': gettext(f'Ваша позиция в рейтинге {len(companies)}')})
print(form.errors)
return JsonResponse(form.errors, status=400)
|
v
def get_companies_info(min_value=None):
revenue_info = get_revenue_info()
if not min_value:
min_value = YearTop1000.objects.all().first().min_value
company_dict = {revenue.company: revenue.company for revenue in revenue_info}
for _ in range(2):
company_info = {}
last_revenues = []
before_last_revenues = []
for company in company_dict:
last_revenue = get_last_or_before_last_revenue(company, 'last')
before_last_revenue = get_last_or_before_last_revenue(company, 'before_last')
growth = calc_growth(last_revenue, before_last_revenue)
if growth > 0:
growth_percent = calc_growth_percent(before_last_revenue, last_revenue)
last_revenues.append(last_revenue)
before_last_revenues.append(before_last_revenue)
company_info[company] = {
'revenue': last_revenue,
'before_last_revenue': before_last_revenue,
'growth': growth,
'growth_percent': growth_percent
}
growth_median = calc_growth_median(last_revenues, before_last_revenues)
filter = YearTop1000.objects.first()
filter.median = growth_median
filter.save(update_fields=['median'])
for company in company_info:
absolute_growth = company_info[company].get('growth')
growth_percent = company_info[company].get('growth_percent')
k = calc_index_k(absolute_growth, growth_median)
company_info[company]['k'] = k
company_info[company]['score'] = calc_score(k, growth_percent)
company_dict = {
company: data
for company, data in company_info.items() if data['score'] >= min_value
}
last_revenues.clear()
before_last_revenues.clear()
sorted_companies = sorted(
company_dict.items(), key=lambda x: x[1]['score'], reverse=True
)
return sorted_companies
|
v
def calc_growth_median(last_revenues, before_last_revenues):
last_revenues.sort()
before_last_revenues.sort()
return statistics.median(last_revenues) - statistics.median(before_last_revenues)
|
V
def get_revenue_info():
year_info = YearTop1000.objects.all().first()
companies_qs = CompanyRevenue.objects.\
filter(Q(year=year_info.last_year,
period=year_info.period,
market_size=year_info.last,
revenue__gte=YearTop1000.MIN_REVENUE[year_info.period]) |
Q(company__see_to_top=True)
)\
.values_list('company_id', flat=True)
companies_qs = CompanyRevenue.objects\
.filter(Q(year=year_info.year_before_last,
period=year_info.period,
market_size=year_info.last,
revenue__gte=YearTop1000.MIN_REVENUE[year_info.period],
company_id__in=companies_qs) | Q(company__see_to_top=True)) \
.values_list('company_id', flat=True)
revenues_qs = CompanyRevenue.objects.filter(
company_id__in=companies_qs,
year__in=(year_info.last_year, year_info.year_before_last),
period='year'
).select_related().order_by('company', 'year')
return revenues_qs
С какого-то момента в изменении БД (непонятно с какого) выкидывает ошибку:
<form id='request-position-form' class="request-form" method="GET" action="{% url 'grow_position' %}">
{% csrf_token %}
{% for field in position_top_1000_form %}
<div class="inputbox">
{{ field }}
<span>{{ field.label_tag }}</span>
</div>
{% endfor %}
<button type="submit" class="btn text-white w-100" style="background: #45D064;">{% trans "Узнать свою позицию" %}
<div class="spinner-border align-top d-none" role="status">
<span class="visually-hidden">{% trans "Загрузка" %}...</span>
</div>
</button>
<div id="request-position-form-error" class="d-none">{% trans "Не удалось получить данные, пожалуйста, перезагрузите страницу" %}</div>
</form>
<div id="request-position-form-error" class="d-none">{% trans "Не удалось получить данные, пожалуйста, перезагрузите страницу" %}