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

Django如何实现数据库有数据时不重复插入API获取的JSON数据

解决方案

你只需要在执行API数据拉取、写入逻辑前,先判断Brands数据表是否为空即可,Django ORM提供了exists()方法可以高效完成这个判断,性能远高于count()统计。

修改后的view.py代码

from django.shortcuts import render
from .models import Brands
import requests

def get_brends(request):
    # 仅当数据表为空时才执行数据拉取和写入
    if not Brands.objects.exists():
        url ='http://makeup-api.herokuapp.com/api/v1/products.json?brand'
        response = requests.get(url)
        data = response.json()
        # 建议用bulk_create批量插入,减少数据库IO次数,提升性能
        brand_list = []
        for result in data:
            brand_data = Brands(
                name=result['name'],
                price=result['price'],
                image_link=result['image_link'],
                brand=result['brand'],
                category=result['category'],
                product_type=result['product_type'],
                description=result['description'],
            )
            brand_list.append(brand_data)
        # 批量写入数据库
        Brands.objects.bulk_create(brand_list)
    
    # 查询所有品牌数据放在逻辑外,避免重复查询
    all_brands = Brands.objects.all().order_by('-id')
    return render(request, 'brands_makeup/brands.html', {"all_brands":all_brands})

额外优化和问题修正

  • 原代码中Brands.object.all()存在拼写错误,应为Brands.objects.all()
  • 用bulk_create批量插入替代循环单条插入,可大幅减少数据库交互次数,提升写入性能
  • 原models.py中的__str__方法返回了元组,不符合Django要求,建议修改为返回字符串格式:
def __str__(self):
    return f"{self.name} | {self.brand} | 价格:{self.price}"
  • 如果后续需要支持增量更新、避免单条数据重复插入,可以把bulk_create替换为循环调用Brands.objects.get_or_create(),按唯一字段(比如name+brand组合)判断是否已存在,存在则跳过,不存在才写入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 01:36:03