django对api的多个newtwork请求导致唯一冲突错误
所以我有一个API,它接受一个关键字并运行一些逻辑,然后将数据插入关键字表。 关键字模型为:django对api的多个newtwork请求导致唯一冲突错误,django,postgresql,Django,Postgresql,所以我有一个API,它接受一个关键字并运行一些逻辑,然后将数据插入关键字表。 关键字模型为: class Keyword(BaseModel): text = models.CharField(max_length=500, unique=True) key_id = models.CharField(max_length=20, null=True, blank=True) def __str__(self): return my_unicode(se
class Keyword(BaseModel):
text = models.CharField(max_length=500, unique=True)
key_id = models.CharField(max_length=20, null=True, blank=True)
def __str__(self):
return my_unicode(self.text)
现在,由于我的前端js代码中存在一些错误,一次单击按钮就发送了两次api请求(这不是什么大问题)。但在后端处理关键字期间,以下代码运行,这会导致UniqueViolation错误:
def get_data_for_keyword(key, region_id, language_id):
# key is the keyword text that we need to save into db which is coming from network request
# Some code
keyword = Keyword.objects.filter(text__iexact=key)
if keyword.exists():
keyword = keyword[0]
# some code
else:
keyword = Keyword(text=key)
keyword.save()
# some code
场景:两个请求带有相同的关键字(由于js错误)。
预期行为:两个请求都检查该关键字在数据库中是否存在,首先运行的请求在数据库中找不到该关键字,而另一个请求在数据库中找到该关键字,并进行进一步处理。
但发生的情况是,不知何故,两个请求都同时执行,并且在筛选时都没有找到该关键字,并且都试图创建并保存该关键字。一个成功了,另一个成功了
django.db.utils.IntegrityError: duplicate key value violates unique constraint "app_keyword_text_31586601_uniq"
DETAIL: Key (text)=(new api) already exists.
这是django预期的行为吗?我的问题是,作为应用程序开发人员,我们需要处理这样的情况吗?还是django应该处理这样的情况。
我使用Postgres作为DB。
如果需要堆栈跟踪,请务必告诉我