Mam kod zapisujący z google books api.
for book_data in data['items']:
volume_info = book_data['volumeInfo']
title = volume_info['title']
genres = volume_info.get('categories')
authors = volume_info.get('authors')
description = volume_info.get('description')
if not Books.objects.filter(title=title).exists():
book = Books.objects.create(title=title, description=description)
# Does authors exists in database?
existing_authors = Authors.objects.filter(author_name__in=authors)
existing_authors_names = {authors.author_name for authors in existing_authors}
# Create a list of missing authors
missing_authors = [
Authors(author_name=author_name)
for author_name in authors
if author_name not in existing_authors_names
]
print(missing_authors)
# Creating author before adding it to relation
if missing_authors:
missing_authors = Authors.objects.bulk_create(missing_authors)
for m in missing_authors:
m.save()
# Adding authors to book relation
book.authors.add(*existing_authors, *missing_authors)
# Does genres exists in database?
existing_genres = Genres.objects.filter(genres__in=genres)
existing_genres_name = {genres.genres for genres in existing_genres}
# Create a list of missing genres
missing_genres = [
Genres(genres=genres)
for genres in genres
if genres not in existing_genres_name
]
# Creating genre before adding it to relation
if missing_genres:
missing_genres = Genres.objects.bulk_create(missing_genres)
for m in missing_genres:
m.save()
# Adding genres to book relation
book.genres.add(*existing_genres, *missing_genres)
Moim problemem jest to że zapisuje on po 2 razy tego samego autora i genre( np. J.R.R. Tolkien, Fiction) ale tylko jeden ma relację z modelem Books. Jak zrobić żeby zapisywało tylko raz Autora i Genre