diff --git a/apps/location/transfer_data.py b/apps/location/transfer_data.py index a5a659c0..cbf5954f 100644 --- a/apps/location/transfer_data.py +++ b/apps/location/transfer_data.py @@ -1,6 +1,6 @@ from django.db.models import Q -from transfer.serializers.location import CountrySerializer, RegionSerializer +from transfer.serializers.location import CountrySerializer, RegionSerializer, CitySerializer from transfer.models import Cities from pprint import pprint @@ -31,10 +31,33 @@ def transfer_regions(): else: pprint(f"Parent regions serializer errors: {serialized_without_subregion.errors}") + regions_with_subregion_queryset = Cities.objects. \ + exclude(Q(subregion_code__isnull=True) | + Q(subregion_code="") | + Q(region_code__isnull=True) | + Q(country_code_2__isnull=True) | + Q(region_code="") | + Q(country_code_2="")). \ + values('region_code', 'country_code_2', 'subregion_code').distinct() + + serialized_with_subregion = RegionSerializer(data=list(regions_with_subregion_queryset.values()), many=True) + if serialized_with_subregion.is_valid(): + serialized_with_subregion.save() + else: + pprint(f"Child regions serializer errors: {serialized_with_subregion.errors}") + + + +def transfer_cities(): + pass + data_types = { "dictionaries": [ transfer_countries, + ], + "tmp": [ transfer_regions, + # transfer_cities ] } diff --git a/apps/transfer/serializers/location.py b/apps/transfer/serializers/location.py index b53cad6a..654dc246 100644 --- a/apps/transfer/serializers/location.py +++ b/apps/transfer/serializers/location.py @@ -39,11 +39,20 @@ class RegionSerializer(serializers.ModelSerializer): ) def validate(self, data): - data['code'] = data.pop('region_code') + if "subregion" in data and data["subregion"] is not None: + try: + parent_region = Region.objects.get(code=data['region_code']) + except Exception as e: + raise ValueError(f"Parent region error with {data}: {e}") + data['parent_region'] = parent_region + data['code'] = data.pop('subregion_code') + + else: + data['code'] = data.pop('region_code') try: country = Country.objects.get(code=data['country_code_2']) except Exception as e: - raise ValueError(f"{data}: {e}") + raise ValueError(f"Country error with {data}: {e}") data["country"] = country del (data['country_code_2']) @@ -58,3 +67,7 @@ class RegionSerializer(serializers.ModelSerializer): except Exception as e: raise ValueError(f"{validated_data}: {e}") return region + + +class CitySerializer(serializers.ModelSerializer): + pass