mpri-webdam/profiles/management/commands/import_events.py

42 lines
1.1 KiB
Python
Raw Normal View History

2018-02-25 11:49:11 +01:00
""" Small module that import events into the database.
"""
import json
from datetime import datetime
from django.core.management.base import BaseCommand
from django.db import models
from profiles.models import Place, Event
def import_file(filename):
with open(filename, mode='r') as file:
data = json.load(file)
for event in data:
import_event(event)
def import_place(_place):
place = Place(
name=_place.get("name", ""),
address=_place.get("address", ""),
lat=float(_place.get("lat", 0)),
lon=float(_place.get("lon", 0))
)
place.save()
return place
def import_event(_event):
if isinstance(_event["place"], str):
place = Place.objects.get(name=_event["place"])
else:
place = import_place(_event["place"])
event = Event(
name=_event.get("name", ""),
date=datetime.strptime(_event.get("date", "01/01/1970 00:00 UTC"), "%d/%m/%Y %H:%M %Z"),
place=place
)
#print(event)
event.save()
class Command(BaseCommand):
def handle(self, *args, **kwargs):
import_file("data/events.json")