Переделки и улучшения

This commit is contained in:
2025-11-21 16:56:58 +03:00
parent 58838614a5
commit 0d239ef1de
11 changed files with 604 additions and 138 deletions

View File

@@ -210,9 +210,9 @@ def _find_or_create_source_by_name_and_distance(
- Совпадает имя (source_name)
2. Для каждого найденного Source проверяет расстояние до новой координаты
3. Если найден Source в радиусе ≤56 км:
- Возвращает его и обновляет coords_average инкрементально
- Возвращает его и обновляет coords_average через метод update_coords_average
4. Если не найден подходящий Source:
- Создает новый Source
- Создает новый Source с типом "стационарные"
Важно: Может существовать несколько Source с одинаковым именем и спутником,
но они должны быть географически разделены (>56 км друг от друга).
@@ -232,7 +232,7 @@ def _find_or_create_source_by_name_and_distance(
parameter_obj__id_satellite=sat,
source__isnull=False,
source__coords_average__isnull=False
).select_related('source', 'parameter_obj')
).select_related('source', 'parameter_obj', 'source__info')
# Собираем уникальные Source из найденных ObjItem
existing_sources = {}
@@ -243,28 +243,30 @@ def _find_or_create_source_by_name_and_distance(
# Проверяем расстояние до каждого существующего Source
closest_source = None
min_distance = float('inf')
best_new_avg = None
for source in existing_sources.values():
if source.coords_average:
source_coord = (source.coords_average.x, source.coords_average.y)
new_avg, distance = calculate_mean_coords(source_coord, coord)
_, distance = calculate_mean_coords(source_coord, coord)
if distance <= RANGE_DISTANCE and distance < min_distance:
min_distance = distance
closest_source = source
best_new_avg = new_avg
# Если найден близкий Source (≤56 км)
if closest_source:
# Обновляем coords_average инкрементально
closest_source.coords_average = Point(best_new_avg, srid=4326)
# Обновляем coords_average через метод модели
closest_source.update_coords_average(coord)
closest_source.save()
return closest_source
# Если не найден подходящий Source - создаем новый
# Если не найден подходящий Source - создаем новый с типом "Стационарные"
from .models import ObjectInfo
stationary_info, _ = ObjectInfo.objects.get_or_create(name="Стационарные")
source = Source.objects.create(
coords_average=Point(coord, srid=4326),
info=stationary_info,
created_by=user
)
return source
@@ -306,7 +308,7 @@ def fill_data_from_df(df: pd.DataFrame, sat: Satellite, current_user=None):
consts = get_all_constants()
df.fillna(-1, inplace=True)
df.sort_values('Дата')
user_to_use = current_user if current_user else CustomUser.objects.get(id=1)
new_sources_count = 0
added_count = 0
@@ -324,7 +326,6 @@ def fill_data_from_df(df: pd.DataFrame, sat: Satellite, current_user=None):
# Извлекаем имя источника
source_name = row["Объект наблюдения"]
# Проверяем кэш: ищем подходящий Source среди закэшированных
found_in_cache = False
for cache_key, cached_source in sources_cache.items():
cached_name, cached_id = cache_key
@@ -336,11 +337,11 @@ def fill_data_from_df(df: pd.DataFrame, sat: Satellite, current_user=None):
# Проверяем расстояние
if cached_source.coords_average:
source_coord = (cached_source.coords_average.x, cached_source.coords_average.y)
new_avg, distance = calculate_mean_coords(source_coord, coord_tuple)
_, distance = calculate_mean_coords(source_coord, coord_tuple)
if distance <= RANGE_DISTANCE:
# Нашли подходящий Source в кэше
cached_source.coords_average = Point(new_avg, srid=4326)
cached_source.update_coords_average(coord_tuple)
cached_source.save()
source = cached_source
found_in_cache = True
@@ -499,6 +500,10 @@ def _create_objitem_from_row(row, sat, source, user_to_use, consts):
# Связываем geo с objitem
geo.objitem = obj_item
geo.save()
# Обновляем дату подтверждения источника
source.update_confirm_at()
source.save()
def add_satellite_list():
@@ -624,7 +629,7 @@ def get_points_from_csv(file_content, current_user=None):
.astype(float)
)
df["time"] = pd.to_datetime(df["time"], format="%d.%m.%Y %H:%M:%S")
df.sort_values('time')
user_to_use = current_user if current_user else CustomUser.objects.get(id=1)
new_sources_count = 0
added_count = 0
@@ -665,11 +670,11 @@ def get_points_from_csv(file_content, current_user=None):
# Проверяем расстояние
if cached_source.coords_average:
source_coord = (cached_source.coords_average.x, cached_source.coords_average.y)
new_avg, distance = calculate_mean_coords(source_coord, coord_tuple)
_, distance = calculate_mean_coords(source_coord, coord_tuple)
if distance <= RANGE_DISTANCE:
# Нашли подходящий Source в кэше
cached_source.coords_average = Point(new_avg, srid=4326)
cached_source.update_coords_average(coord_tuple)
cached_source.save()
source = cached_source
found_in_cache = True
@@ -834,6 +839,10 @@ def _create_objitem_from_csv_row(row, source, user_to_use):
# Связываем geo с objitem
geo_obj.objitem = obj_item
geo_obj.save()
# Обновляем дату подтверждения источника
source.update_confirm_at()
source.save()
def get_vch_load_from_html(file, sat: Satellite) -> None: