Advertisement
megalaren

Untitled

Oct 30th, 2020
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. # ==============================  file 'xlsx_group_parser.py'  ==============================
  2. from openpyxl import load_workbook
  3. from posts.models import Group
  4.  
  5.  
  6. def XLSXGroupParser(file):
  7.     wb = load_workbook(file)
  8.     ws = wb.active
  9.     rows = ws.values
  10.     headlines = next(rows)
  11.     index_of_headline = {'title': headlines.index('title'),
  12.                          'slug': headlines.index('slug'),
  13.                          'description': headlines.index('slug')}
  14.     groups = []
  15.     for row in rows:
  16.         group = Group(title=row[index_of_headline['title']],
  17.                       slug=row[index_of_headline['slug']],
  18.                       description=row[index_of_headline['description']])
  19.         if (not group.title or group.title.isspace() or
  20.                 not group.slug or group.slug.isspace()):
  21.             continue
  22.         groups.append(group)
  23.     return groups
  24.  
  25.  
  26. # ==============================  file 'xlsx_group_import.py'  ==============================
  27. from django.core.management.base import BaseCommand
  28. from posts.parsers.xlsx_group_parser import XLSXGroupParser
  29.  
  30.  
  31. class Command(BaseCommand):
  32.     help = 'Import groups from xlsx file'
  33.  
  34.     def add_arguments(self, parser):
  35.         parser.add_argument('file', type=str)
  36.  
  37.     def handle(self, *args, **options):
  38.         file_path = options['file']
  39.         groups = XLSXGroupParser(file_path)
  40.         for group in groups:
  41.             group.save()
  42.             self.stdout.write(f'Группа {group.title} сохранена')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement