You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django REST项目中如何将API商品库存数据存入MySQL数据库

解决方案

视图集选择

优先选ModelViewSet,它自带CRUD基础实现,如果你只需要创建功能,可通过http_method_names限制仅允许POST请求;若仅需批量创建,用CreateAPIView也完全够用。推荐用ModelViewSet,方便后续扩展查询、更新等操作。

序列化器优化

你当前的序列化器重复定义了字段,且store作为外键,电商API返回的数据里并没有这个字段,需要调整:

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ['store', 'offer_id', 'name', 'present', 'reserved']
        # 将store设为只读,API数据无此字段,后续在视图中手动赋值
        read_only_fields = ['store']

    # 若电商API未返回name字段,设置允许为空或默认值
    name = serializers.CharField(required=False, default="")

自定义Create方法(支持批量创建/更新)

电商API返回批量数据,且库存需更新而非重复创建,因此要实现**Upsert(插入或更新)**逻辑:

视图代码

from rest_framework import viewsets, status
from rest_framework.response import Response
from .models import Product, Store
from .serializers import ProductSerializer

class ProductInventoryViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    # 仅允许POST请求,限定操作范围
    http_method_names = ['post']

    def create(self, request, *args, **kwargs):
        # 获取关联店铺(这里假设从请求体的store_id参数获取,可根据实际调整,比如从URL参数/当前用户绑定店铺取)
        store_id = request.data.get('store_id')
        try:
            store = Store.objects.get(id=store_id)
        except Store.DoesNotExist:
            return Response({"error": "店铺不存在"}, status=status.HTTP_400_BAD_REQUEST)

        inventory_data = request.data.get('inventory')
        # 兼容单个数据传入的情况,统一转为列表处理
        if not isinstance(inventory_data, list):
            inventory_data = [inventory_data]

        products = []
        for item in inventory_data:
            # 根据offer_id和店铺查询商品,存在则更新,不存在则创建
            product, created = Product.objects.get_or_create(
                store=store,
                offer_id=item['offer_id'],
                defaults={
                    'name': item.get('name', ""),
                    'present': item['present'],
                    'reserved': item['reserved']
                }
            )
            if not created:
                product.present = item['present']
                product.reserved = item['reserved']
                product.save()
            products.append(product)

        serializer = self.get_serializer(products, many=True)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

请求示例(匹配你的API数据格式)

发送POST请求,请求体格式如下:

{
    "store_id": 1,  // 替换为实际店铺ID
    "inventory": [
        {
            "offer_id":"1-100-3-0",
            "present":5,
            "reserved":1
        },
        {
            "offer_id":"1-101-3-9",
            "present":0,
            "reserved":0
        }
    ]
}

关键说明

  • 店铺关联逻辑:可根据实际场景调整店铺获取方式,比如从当前登录用户绑定的店铺直接获取,无需传递store_id。
  • Upsert逻辑:通过get_or_create避免重复创建相同offer_id+store的商品,已有商品直接更新库存数据。
  • 批量兼容:同时支持单个和批量数据传入,统一处理逻辑。

内容的提问来源于stack exchange,提问作者Iren E

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 01:05:19