From 7531b9fd5b5902a8b552bd010f245b492fd917b2 Mon Sep 17 00:00:00 2001 From: colaftc Date: Mon, 12 Jan 2026 13:41:41 +0800 Subject: [PATCH] fix: product sync error cause duplicate data --- api_v1/tasks.py | 15 +++++++++++---- docs/2026-01-11_summary.md | 6 ++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/api_v1/tasks.py b/api_v1/tasks.py index 7b9138b..0c5d2be 100644 --- a/api_v1/tasks.py +++ b/api_v1/tasks.py @@ -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: diff --git a/docs/2026-01-11_summary.md b/docs/2026-01-11_summary.md index e606e3f..6113633 100644 --- a/docs/2026-01-11_summary.md +++ b/docs/2026-01-11_summary.md @@ -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`)