From 06b12f94279f8132daa8ca46e3b387d5da4a947a Mon Sep 17 00:00:00 2001 From: littlewolf Date: Sat, 26 Oct 2019 09:18:45 +0300 Subject: [PATCH] Add country transfer --- apps/location/transfer_data.py | 9 +++++++-- apps/transfer/serializers/location.py | 20 +++++++++++--------- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/apps/location/transfer_data.py b/apps/location/transfer_data.py index e4ac90a7..db020e7a 100644 --- a/apps/location/transfer_data.py +++ b/apps/location/transfer_data.py @@ -6,7 +6,8 @@ from pprint import pprint def transfer_countries(): - queryset = Cities.objects.exclude(country_code_2__isnull=True).values_list("country_code_2", flat=True).distinct() + queryset = Cities.objects.exclude(Q(country_code_2__isnull=True) | Q(country_code_2=""))\ + .values_list("country_code_2", flat=True).distinct() serialized_data = CountrySerializer(data=list(queryset.values()), many=True) if serialized_data.is_valid(): @@ -17,7 +18,11 @@ def transfer_countries(): def transfer_regions(): regions_without_subregion_queryset = Cities.objects.\ - exclude(Q(subregion_code__isnull=False) | Q(region_code__isnull=True) | Q(country_code_2__isnull=True)).\ + exclude(Q(subregion_code__isnull=False) | + 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_without_subregion = RegionSerializer(data=list(regions_without_subregion_queryset.values()), many=True) diff --git a/apps/transfer/serializers/location.py b/apps/transfer/serializers/location.py index 61df6baf..b53cad6a 100644 --- a/apps/transfer/serializers/location.py +++ b/apps/transfer/serializers/location.py @@ -40,19 +40,21 @@ class RegionSerializer(serializers.ModelSerializer): def validate(self, data): data['code'] = data.pop('region_code') - if "country_code_2" in data and data["country_code_2"] is not None: - try: - country = Country.objects.get(code=data['country_code_2']) - data.country = country - del (data['country_code_2']) - - except Country.DoesNotExist as e: - print(f"Country error: {e}") + try: + country = Country.objects.get(code=data['country_code_2']) + except Exception as e: + raise ValueError(f"{data}: {e}") + data["country"] = country + del (data['country_code_2']) del(data['subregion_code']) + return data def create(self, validated_data): # Some regions may be already in database - region, _ = Region.objects.get_or_create(**validated_data) + try: + region, _ = Region.objects.get_or_create(**validated_data) + except Exception as e: + raise ValueError(f"{validated_data}: {e}") return region