簡體   English   中英

Django模型保存兩次

[英]Django model is saving twice

我正在嘗試保存Authors模型,但是它將兩次保存到數據庫中。 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_missing_authors中,對嗎?

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

執行查詢后, bulk_create方法自動保存結果。

將代碼更改為此:

if missing_authors:
    Authors.objects.bulk_create(missing_authors)


''' remove these lines
    for m in missing_authors:
        m.save()

#not sure what this line is doing exactly, but it might be causing your problem
book.authors.add(*existing_authors, *missing_authors)
'''

更新

如果您可以為author_name列設置unique=True ,請嘗試以下操作:

class Authors(models.Model):
    author_name = models.CharField(max_length=200, unique=True)


Authors.objects.bulk_create(missing_authors, ignore_conflicts=True)
for m in missing_authors:
    m.save()

book.authors.add(*existing_authors, *missing_authors)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM