首页 > 解决方案 > 如果数据库中有数据,如何写一个条件,即函数不执行?姜戈

问题描述

每次运行我的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。

标签: pythonjsondjangodjango-viewspython-requests

解决方案


如果我猜对了您目前的情况,那么也许我可以为您提供帮助。

我认为无论如何您都希望您的 api 返回品牌。这就是为什么在表为空时保存数据的原因。换句话说,您的情况可以通过在表格中提供默认品牌列表来解决。换句话说,在 django 中播种数据表是您真正想要的。

如果我是对的,那么我建议你访问这个。 在 Django 中,您可以在不总是生成迁移的情况下运行种子数据吗?


推荐阅读