Я пытаюсь сохранить модель авторов, но она дважды сохраняется в базе данных.
views.py
........................
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
]
# Creating author before adding it to relation
if missing_authors:
missing_authors = Authors.objects.bulk_create(missing_authors)
print(missing_authors)
for m in missing_authors:
m.save()
# Adding to relation
book.authors.add(*existing_authors, *missing_authors)
..........................
Я думаю, проблема в m в отсутствующих_утюрах, верно?
models.py
class Authors(models.Model):
author_name = models.CharField(max_length=200)
def __str__(self):
return self.author_name
class Books(models.Model):
title = models.CharField(max_length=300)
description = models.TextField(blank=True, null=True)
authors = models.ManyToManyField(Authors, blank=True)
genres = models.ManyToManyField(Genres, blank=True)
def __str__(self):
return self.title
база данных sqllite3
Версия Django - 2.2.1