from django.core.management.base import BaseCommand from pytz import timezone as py_tz from timezonefinder import TimezoneFinder from establishment.models import Establishment class Command(BaseCommand): help = 'Attach correct timestamps according to coordinates to existing establishments' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.tf = TimezoneFinder(in_memory=True) def handle(self, *args, **options): for establishment in Establishment.objects.prefetch_related('address').all(): if establishment.address and establishment.address.latitude and establishment.address.longitude: establishment.tz = py_tz(self.tf.certain_timezone_at(lng=establishment.address.longitude, lat=establishment.address.latitude)) establishment.save() self.stdout.write(self.style.SUCCESS(f'Attached timezone {establishment.tz} to {establishment}')) else: self.stdout.write(self.style.WARNING(f'Establishment {establishment} has no coordinates' f'passing...'))