gault-millau/apps/establishment/management/commands/add_establishment_currency.py
2019-11-03 15:34:53 +03:00

40 lines
1.6 KiB
Python

from django.core.management.base import BaseCommand
import requests
from establishment.models import Establishment
from main.models import Currency
from location.models import Country
class Command(BaseCommand):
help = 'Add currency to new db'
def handle(self, *args, **kwargs):
count = 0
url = 'https://restcountries.eu/rest/v2/name/{country}'
countries = Country.objects.all()
for country in countries:
country_name = country.name_translated
resp = requests.get(url=url.format(country=country_name))
if resp.status_code == requests.codes.ok:
country_list = resp.json()
if isinstance(country_list, list):
currency_dict = country_list[0].get("currencies")[0]
if currency_dict:
name = currency_dict.get("name")
if name:
currency, created = Currency.objects.get_or_create(
slug=currency_dict.get("name").lower(),
)
if created:
currency.name = {"en-GB": name},
currency.sign = currency_dict.get("symbol"),
currency.save()
establishments = Establishment.objects.filter(address__city__country=country)
establishments.update(currency=currency)
count += 1
self.stdout.write(self.style.WARNING(f'Created/updated {count} objects.'))