Skip to content

Commit

Permalink
CSV importer added
Browse files Browse the repository at this point in the history
  • Loading branch information
brodul committed Feb 27, 2013
1 parent 80d34e6 commit 30cb017
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
Empty file.
Empty file.
71 changes: 71 additions & 0 deletions liby/books/management/commands/importbooks.py
@@ -0,0 +1,71 @@
import csv

from django.core.management.base import BaseCommand
from django.db.utils import IntegrityError

from liby.books.models import Book, Author, Genre


class Command(BaseCommand):
args = '<csv_file>'
help = 'Imports books from csv'

def handle(self, *args, **options):
csv_file = args[0]
with open(csv_file) as f:
reader = csv.DictReader(f)

for line in reader:
if not line["Naslov"]:
continue
book = Book()
book.title = line["Naslov"]

if line["Letnica"]:
book.pub_date = line["Letnica"]
if line["ISBN"]:
book.isbn = line["ISBN"]

book_authors = []

raw_authors = line["Avtor"]
raw_authors = raw_authors.replace("et al.", "")
raw_authors = raw_authors.replace("et al", "")
authors = raw_authors.split(";")
authors = map(str.strip, authors)

book.save()

for author_name in authors:
try:
author = Author()
author.name = author_name
author.save()
book_authors.append(author)
except IntegrityError:
book_authors.append(Author.objects.get(name=author_name))

book.authors.add(*book_authors)
book.save()

# DRY TODO

raw_genres = line["Zanr"]
genres = raw_genres.split(",")
genres = map(str.strip, genres)
if not genres[0]:
continue

book_genres = []

for name in genres:
try:
genre = Genre()
genre.genre_name = name
genre.save()
book_genres.append(genre)
except IntegrityError:
book_genres.append(Genre.objects.get(genre_name=name))

book.genres.add(*book_genres)
book.save()

0 comments on commit 30cb017

Please sign in to comment.