45 lines
1.9 KiB
Python
45 lines
1.9 KiB
Python
from django.core.management.base import BaseCommand
|
|
import requests
|
|
from establishment.models import Establishment
|
|
from main.models import Currency
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = 'Add currency to new db'
|
|
|
|
def handle(self, *args, **kwargs):
|
|
count = 0
|
|
|
|
queryset = Establishment.objects.all()
|
|
url = 'https://restcountries.eu/rest/v2/name/{country}'
|
|
for est in queryset:
|
|
if not est.currency and est.address and est.address.city and est.address.city.country:
|
|
|
|
try:
|
|
country = est.address.city.country.name_translated
|
|
resp = requests.get(url=url.format(country=country))
|
|
except requests.exceptions.Timeout:
|
|
continue
|
|
except Establishment.DoesNotExist:
|
|
continue
|
|
else:
|
|
if resp.status_code == requests.codes.ok:
|
|
country_list = resp.json()
|
|
if isinstance(country_list, list):
|
|
currency_dict = country_list[0].get("currency")
|
|
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()
|
|
est.currency = currency
|
|
est.save()
|
|
count += 1
|
|
|
|
self.stdout.write(self.style.WARNING(f'Created/updated {count} objects.'))
|