Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
71 additions
and
0 deletions.
There are no files selected for viewing
Empty file.
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() |