【问题标题】:Django model is saving twiceDjango模型保存两次
【发布时间】:2019-10-06 06:50:18
【问题描述】:

我正在尝试保存 Authors 模型,但它一直保存两次到数据库中。 视图.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)
..........................

我认为问题在于 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

【问题讨论】:

  • 如果您提供您的环境可能会有所帮助:您的模型、数据库类型和 Django 版本。使用bulk_create 时有一些注意事项,如您所见here。似乎bulk_create 正在写一次,当你打电话给m.save() 时,你又在写一次。
  • 添加模型和休息

标签: python django


【解决方案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)

【讨论】:

  • book.authors.add 正在将创建的作者模型添加到 M2M 关系。当我删除for循环时,它会引发错误“无法添加“”:实例在数据库“默认”上,值在数据库“无”上”
  • 您可以尝试删除book.authors.add 行吗? this 问题解释了该错误。
  • 另外,你能用你的模型更新你的问题吗?如果您必须保留book.authors.add 行,我还能想到其他解决方法。
  • 当我删除它时,它保存得很好,但是 Books 模型没有作者。还添加了模型。
  • 更新了模型,现在它说:唯一约束失败:api_authors.author_name
猜你喜欢
  • 2016-10-03
  • 1970-01-01
  • 1970-01-01
  • 2019-05-31
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 2011-01-21
  • 2016-01-24
相关资源
最近更新 更多