Fix interests import

This commit is contained in:
Rémi Oudin 2018-02-25 21:20:52 +01:00
parent 15323c3465
commit 93b235cb6c

View file

@ -0,0 +1,52 @@
""" 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
from django.core.exceptions import ObjectDoesNotExist
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 = []
print(_interest)
for keyword in _interest.get("keywords", []):
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)
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", ""),
)
interest.save()
for keyword in keywords:
print(keyword)
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):
import_file("data/interests.json")