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

52 lines
1.6 KiB
Python
Raw Normal View History

2018-02-25 16:10:22 +01:00
""" Small module that import interests into the database.
"""
import json
from datetime import datetime
from django.core.management.base import BaseCommand
from django.db import models
2018-02-25 21:20:52 +01:00
from django.core.exceptions import ObjectDoesNotExist
2018-02-25 16:10:22 +01:00
from profiles.models import Keyword, Interest, Place, Website, Event
def import_file(filename):
with open(filename, mode='r') as file:
data = json.load(file)
for interest in data:
import_interest(interest)
def import_interest(_interest):
keywords = []
places = []
websites = []
for keyword in _interest.get("keywords", []):
2018-02-25 21:20:52 +01:00
try:
stored = Keyword.objects.get(text=keyword["keyword"])
keywords.append(stored)
except ObjectDoesNotExist:
new_keyword = Keyword(text=keyword["keyword"])
new_keyword.save()
keywords.append(new_keyword)
print("New keyword %s" % new_keyword)
2018-02-25 16:10:22 +01:00
for place in _interest.get("places", []):
places.append(Place.objects.get(name=place["place"]))
for website in _interest.get("websites", []):
websites.append(Website.objects.get(name=website["website"]))
interest = Interest(
name=_interest.get("name", ""),
)
2018-02-25 21:20:52 +01:00
interest.save()
2018-02-25 16:10:22 +01:00
for keyword in keywords:
2018-02-25 21:20:52 +01:00
print(keyword)
2018-02-25 16:10:22 +01:00
interest.keywords.add(keyword)
for place in places:
interest.places.add(place)
for website in websites:
interest.websites.add(website)
interest.save()
class Command(BaseCommand):
def handle(self, *args, **kwargs):
2018-02-25 21:20:52 +01:00
import_file("data/interests.json")