modify script add_currency

This commit is contained in:
Dmitriy Kuzmenko 2019-11-03 15:24:03 +03:00
parent 1856589427
commit b88c0d5213

View File

@ -2,6 +2,7 @@ from django.core.management.base import BaseCommand
import requests import requests
from establishment.models import Establishment from establishment.models import Establishment
from main.models import Currency from main.models import Currency
from location.models import Country
class Command(BaseCommand): class Command(BaseCommand):
@ -10,19 +11,13 @@ class Command(BaseCommand):
def handle(self, *args, **kwargs): def handle(self, *args, **kwargs):
count = 0 count = 0
queryset = list(Establishment.objects.filter(address__city__country__isnull=False))
url = 'https://restcountries.eu/rest/v2/name/{country}' url = 'https://restcountries.eu/rest/v2/name/{country}'
for est in queryset: countries = Country.objects.all()
if not est.currency: for country in countries:
try:
country = est.address.city.country.name_translated country_name = country.name_translated
resp = requests.get(url=url.format(country=country)) resp = requests.get(url=url.format(country=country_name))
except requests.exceptions.Timeout:
continue
except Establishment.DoesNotExist:
continue
else:
if resp.status_code == requests.codes.ok: if resp.status_code == requests.codes.ok:
country_list = resp.json() country_list = resp.json()
if isinstance(country_list, list): if isinstance(country_list, list):
@ -37,8 +32,8 @@ class Command(BaseCommand):
currency.name = {"en-GB": name}, currency.name = {"en-GB": name},
currency.sign = currency_dict.get("symbol"), currency.sign = currency_dict.get("symbol"),
currency.save() currency.save()
est.currency = currency establishments = Establishment.objects.filter(address__city__country=country)
establishments.update(currency=currency)
count += 1 count += 1
Establishment.objects.bulk_update(queryset, ['currency'])
self.stdout.write(self.style.WARNING(f'Created/updated {count} objects.')) self.stdout.write(self.style.WARNING(f'Created/updated {count} objects.'))