spejstore-new/storage/management/commands/importbooks.py

32 lines
1.1 KiB
Python
Raw Permalink Normal View History

from django.core.management.base import BaseCommand, CommandError
from storage.models import Item
from io import StringIO
import csv
2023-07-11 13:34:35 +00:00
class Command(BaseCommand):
2023-07-11 13:34:35 +00:00
help = "Imports book library from specified wiki page dump"
def add_arguments(self, parser):
2023-07-11 13:34:35 +00:00
parser.add_argument("parent")
parser.add_argument("file")
def handle(self, *args, **options):
2023-07-11 13:34:35 +00:00
with open(options["file"]) as fd:
sio = StringIO(fd.read())
2023-07-11 13:34:35 +00:00
reader = csv.reader(sio, delimiter="|")
parent = Item.objects.get(pk=options["parent"])
for line in reader:
line = list(map(str.strip, line))
item = Item(parent=parent)
item.name = line[2]
2023-07-11 13:34:35 +00:00
item.props["author"] = line[1]
item.props["owner"] = line[3]
item.props["can_borrow"] = line[4]
item.props["borrowed_by"] = line[5]
item.save()
2023-07-11 13:34:35 +00:00
self.stdout.write(self.style.NOTICE("Book added: %r") % item)
2023-07-11 13:34:35 +00:00
self.stdout.write(self.style.SUCCESS("Successfully imported data"))