【发布时间】:2020-08-09 06:27:09
【问题描述】:
我已经阅读了很多关于如何在 Django 中使数据库/模型独一无二的文章,而且这些文章似乎都有效。但是,我没有看到任何帖子讨论避免向数据库添加重复条目的有效方法。
我的模型如下所示:
# from app.models
class TestModel(models.Model):
text = models.TextField(unique=True, null=True)
fixed_field = models.TextField()
我目前避免添加重复条目而不会出错的方法如下。
# from app.views
posts = ["one", "two", "three"]
fixed_field = "test"
for post in posts:
try:
TestModel(text=post, fixed_field = fixed_field).save()
except IntegrityError:
pass
如果我不这样做,我会得到一个 IntegrityError。有什么办法可以提高效率吗?
【问题讨论】: