Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sanjmen/0963fe3b4bbe1cf55742e936d070f73c to your computer and use it in GitHub Desktop.
Save sanjmen/0963fe3b4bbe1cf55742e936d070f73c to your computer and use it in GitHub Desktop.
json-response-parse-store-db
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
import requests
from books.models import Book, Author, Reviewer, Genre, Editorial, Tag
from books.utils import get_urls_as_text
class Command(BaseCommand):
help = 'Imports the books from a dataset'
def handle(self, *args, **options):
res = requests.get(settings.BOOKS_API_URL)
if res.status_code != 200:
raise CommandError('Cannot retrieve dataset, please try later!')
data = res.json()
count = 0
for item in data:
author, _ = Author.objects.get_or_create(name=item.get('author'))
reviewer, _ = Reviewer.objects.get_or_create(name=item.get('reviewer'), link=item.get('reviewer_link'))
genre, _ = Genre.objects.get_or_create(name=item.get('genre'))
editorial, _ = Editorial.objects.get_or_create(name=item.get('editorial'))
book, created = Book.objects.get_or_create(
title=item.get('title'),
genre=genre,
reviewer=reviewer,
author=author,
links=get_urls_as_text(item.get('links', [])),
external_links=get_urls_as_text(item.get('external_links', [])),
contacted=item.get('contacted', False),
editorial=editorial,
text=item.get('text'),
isbn=item.get('isbn'),
slug=item.get('slug'),
image=item.get('image'),
thumbnail=item.get('thumbnail'),
)
for t in item.get('tags'):
obj, _ = Tag.objects.get_or_create(name=t)
book.tags.add(obj)
if created:
count += 1
self.stdout.write(self.style.SUCCESS(f'Created {count} books!'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment