python - 如果数据库中有数据,如何写一个条件,即函数不执行?姜戈
问题描述
每次运行我的Django 应用程序时,都会将相同的数据插入数据库。我只想在第一次包含数据时,基(表)中没有值。我从API 和 Json 获取数据。
视图.py
from django.shortcuts import render, HttpResponse
from .models import Brands
import requests
def get_brends(request):
all_brands = {}
url ='http://makeup-api.herokuapp.com/api/v1/products.json?brand'
response = requests.get(url)
data = response.json()
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_data.save()
all_brands=Brands.object.all().order_by('-id')
return render(request, 'brands_makeup/brands.html', { "all_brands":all_brands})
模型.py
class Brands(models.Model):
name = models.CharField(max_length=100, default="None")
price = models.DecimalField(decimal_places=3,max_digits=4,null=True,blank=True)
image_link = models.CharField( max_length=50, blank = True, null = True)
brand = models.CharField( max_length=150, blank = True, null = True)
category = models.CharField( max_length=150, blank = True, null = True)
product_type = models.CharField( max_length=150, blank = True, null = True)
description = models.CharField( max_length=1500, blank = True, null = True)
def __str__(self):
return self.name , self.price , self.category , self.brand
当数据库为空时,我只尝试在我的数据库中包含一次 JSON。
解决方案
如果我猜对了您目前的情况,那么也许我可以为您提供帮助。
我认为无论如何您都希望您的 api 返回品牌。这就是为什么在表为空时保存数据的原因。换句话说,您的情况可以通过在表格中提供默认品牌列表来解决。换句话说,在 django 中播种数据表是您真正想要的。
如果我是对的,那么我建议你访问这个。 在 Django 中,您可以在不总是生成迁移的情况下运行种子数据吗?
推荐阅读
- ios - 在“DatePicker *”类型的对象上找不到属性“overrideUserInterfaceStyle”
- java - SQLite 不会删除表
- c# - 无法从 appsettings 获取对象列表
- python - 在 Python 的子进程命令行中使用 osmtogeosjon 将 OSM 文件转换为 geojson 文件
- jenkins - Jenkins 中缺少管道选项卡
- node.js - MongoDB/Mongoose 断开连接时出现未处理错误 - 为什么它不触发 ('error') 事件?
- vue.js - 对象上的 Vuex 状态更改不会触发重新渲染
- python - 无法将数据框列的数据类型更改为 int
- google-colaboratory - Google colab 错误 - 笔记本加载错误:
- sql - SQL:在选择中使用 Lag/Lead 结果两次