forked from erp-dev/erp
fix: product sync error cause duplicate data
This commit is contained in:
@@ -197,12 +197,19 @@ def _upsert_product(product_data, merchant, category):
|
||||
if segment_decimal is not None:
|
||||
defaults['segment_size'] = segment_decimal
|
||||
|
||||
product_obj, created = basic_models.Product.objects.get_or_create(
|
||||
# 使用 filter().first() 替代 get_or_create,容忍重复数据
|
||||
product_obj = basic_models.Product.objects.filter(
|
||||
merchant=merchant,
|
||||
human_id=product_data.uid,
|
||||
defaults=defaults,
|
||||
)
|
||||
if created:
|
||||
).first()
|
||||
|
||||
if product_obj is None:
|
||||
# 不存在,创建新记录
|
||||
product_obj = basic_models.Product.objects.create(
|
||||
merchant=merchant,
|
||||
human_id=product_data.uid,
|
||||
**defaults,
|
||||
)
|
||||
return True
|
||||
|
||||
if not product_obj.from_mdy:
|
||||
|
||||
@@ -88,6 +88,12 @@ MIDDLEWARE = [
|
||||
- `jobs_status_summary`: 按下一待执行状态分组
|
||||
- `jobs_last_status_summary`: 按最后完成状态分组(未开始时 `state_name` 为空字符串)
|
||||
|
||||
### 8. 修复 `_upsert_product` 重复数据问题
|
||||
|
||||
修改 `api_v1/tasks.py` 中的 `_upsert_product` 函数,使用 `filter().first()` 替代 `get_or_create`,容忍数据库中存在重复的 `(merchant, human_id)` 记录。
|
||||
|
||||
原因:`Product` 模型没有设置 `unique_together = ('merchant', 'human_id')` 约束,多同步源可能导致重复数据,`get_or_create` 会抛出 `MultipleObjectsReturned` 错误。
|
||||
|
||||
## 待办事项
|
||||
|
||||
- [ ] 执行数据库迁移 (`uv run python manage.py migrate`)
|
||||
|
||||
Reference in New Issue
Block a user