gault-millau/apps/establishment/management/commands/add_establishment_currency.py
2019-11-12 04:09:57 +03:00

43 lines
1.7 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
from django.template.defaultfilters import slugify
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["en-GB"]
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['name']
if name:
slug = slugify(name)
code = currency_dict['code']
currency, _ = Currency.objects.get_or_create(
slug=slug,
)
currency.name = {"en-GB": name}
currency.code = code
currency.sign = currency_dict["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.'))