如何保存在数据库中的Django模型的数据? [英] how to save data in the db django model?

查看:350
本文介绍了如何保存在数据库中的Django模型的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天,我真的不能明白我在做什么错在这里。我用这个功能基本视图存储与Django模型数据库废我的数据,但现在它不保存任何更多。我真的不能明白为什么。任何想法?

 高清weather_fetch(要求):
    上下文=无
    corrected_rainChance =无
    URL ='http://weather.news24.com/sa/cape-town
    extracted_city = url.split('/')[ - 1]
    城市= extracted_city.replace(' - ',)
    打印(市)
    url_request =的urlopen(URL)
    汤= BeautifulSoup(url_request.read(),'html.parser')
    city​​_list = soup.find(ID =ctl00_WeatherContentHolder_ddlCity)
    city​​_as_on_website = city_list.find(文= re.compile(市,如re.I))。父
    city​​Id = city_as_on_website ['值']
    json_url =htt​​p://weather.news24.com/ajaxpro/TwentyFour.Weather.Web.Ajax,App_$c$c.ashx    标题= {
        内容类型:text / plain的;字符集= UTF-8,
        主机:weather.news24.com',
        原产地:http://weather.news24.com',
        引用站点:URL,
        用户代理:Mozilla的/ 5.0(X11; Linux的i686的)为AppleWebKit / 537.36(KHTML,例如Gecko)Ubuntu的铬/ 48.0.2564.82铬/ Safari浏览器48.0.2564.82 / 537.36',
        X-AjaxPro的法':'GetCurrentOne'}    有效载荷= {
        cityId:cityId
    }
    request_post = requests.post(json_url,标题=标题,数据= json.dumps(负载))
    数据=应用re.sub(R新日期\\(日期\\ .UTC \\((\\ d +),(\\ D +),(\\ D +),(\\ D +),(\\ D +),(\\ D +),(\\ D +)\\)\\),convert_date,request_post.text)
    数据= data.strip(; / *)
    数据= json.loads(数据)
    预测数据= ['预测']
    如果预测[降雨] =='*':
        rainChance = 0
        corrected_rainChance = rainChance
    其他:
        尝试:
            OBJ = WeatherData.objects.get_or_create(
                min_temp =预测[LowTemp],HIGH_TEMP =预测[HighTemp],
                日期=预测[日] = WIND_SPEED预测[风速],雨= corrected_rainChance
            )
        除了WeatherData.DoesNotExist:
            OBJ = WeatherData.objects.get_or_create(
                min_temp =预测[LowTemp],HIGH_TEMP =预测[HighTemp],
                日期=预测[日] = WIND_SPEED预测[风速],
                雨= corrected_rainChance
            )
            obj.save()
            上下文= {语境:OBJ}
            打印(上下文)
    返回渲染(请求,forecastApp /页/ fetch_weather.html',上下文)类WeatherData(models.Model):
    日期= models.DateTimeField(默认值= timezone.now)
    WIND_SPEED = models.DecimalField(max_digits = 3,decimal_places = 1)
    HIGH_TEMP = models.DecimalField(max_digits = 3,decimal_places = 1)
    min_temp = models.DecimalField(max_digits = 3,decimal_places = 1)
    雨= models.IntegerField(默认值为0)    高清__str __(个体经营):
        回报'。加入(STR([self.date.month,self.date.day,self.date.year]))


解决方案

有肯定是有问题,你的尝试/除块。娱您code ++工程,直到创建对象,则应在该部分更改为:

 如果预测[降雨] =='*':
    rainChance = 0
    corrected_rainChance = rainChance
其他:
    OBJ = WeatherData.objects.get_or_create(
            min_temp =预测[LowTemp],HIGH_TEMP =预测[HighTemp],
            日期=预测[日] = WIND_SPEED预测[风速],雨= corrected_rainChance
        )
    #obj.save() - >你不需要再次保存obj的。
    上下文= {语境:OBJ}
    打印(上下文)

Good day, I can't really understand what I'm doing wrong in here. I was using this function base view to store my scrap data in the database with the django model, but now it's not saving any more. I can't really understand why. Any idea?

def weather_fetch(request):
    context = None
    corrected_rainChance = None
    url = 'http://weather.news24.com/sa/cape-town'
    extracted_city = url.split('/')[-1]
    city = extracted_city.replace('-', " ")
    print(city)
    url_request = urlopen(url)
    soup = BeautifulSoup(url_request.read(), 'html.parser')
    city_list = soup.find(id="ctl00_WeatherContentHolder_ddlCity")
    city_as_on_website = city_list.find(text=re.compile(city, re.I)).parent
    cityId = city_as_on_website['value']
    json_url = "http://weather.news24.com/ajaxpro/TwentyFour.Weather.Web.Ajax,App_Code.ashx"

    headers = {
        'Content-Type': 'text/plain; charset=UTF-8',
        'Host': 'weather.news24.com',
        'Origin': 'http://weather.news24.com',
        'Referer': url,
        'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/48.0.2564.82 Chrome/48.0.2564.82 Safari/537.36',
        'X-AjaxPro-Method': 'GetCurrentOne'}

    payload = {
        "cityId": cityId
    }
    request_post = requests.post(json_url, headers=headers, data=json.dumps(payload))
    data = re.sub(r"new Date\(Date\.UTC\((\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)\)\)", convert_date, request_post.text)
    data = data.strip(";/*")
    data = json.loads(data)
    forecast = data['Forecast']
    if forecast["Rainfall"] == '*':
        rainChance = 0
        corrected_rainChance = rainChance
    else:
        try:
            obj = WeatherData.objects.get_or_create(
                min_temp=forecast["LowTemp"], high_temp=forecast["HighTemp"],
                date=forecast["Date"], wind_speed=forecast["WindSpeed"], rain=corrected_rainChance
            )
        except WeatherData.DoesNotExist:
            obj = WeatherData.objects.get_or_create(
                min_temp=forecast["LowTemp"], high_temp=forecast["HighTemp"],
                date=forecast["Date"], wind_speed=forecast["WindSpeed"],
                rain=corrected_rainChance
            )
            obj.save()
            context = {'context': obj}
            print(context)
    return render(request, 'forecastApp/pages/fetch_weather.html', context)

class WeatherData(models.Model):
    date = models.DateTimeField(default=timezone.now)
    wind_speed = models.DecimalField(max_digits=3, decimal_places=1)
    high_temp = models.DecimalField(max_digits=3, decimal_places=1)
    min_temp = models.DecimalField(max_digits=3, decimal_places=1)
    rain = models.IntegerField(default=0)

    def __str__(self):
        return ' '.join(str([self.date.month, self.date.day, self.date.year]))

解决方案

There is definitely a problem with your try/except block. Amusing your code works until the object creation, you should change that part to:

if forecast["Rainfall"] == '*':
    rainChance = 0
    corrected_rainChance = rainChance
else:
    obj = WeatherData.objects.get_or_create(
            min_temp=forecast["LowTemp"], high_temp=forecast["HighTemp"],
            date=forecast["Date"], wind_speed=forecast["WindSpeed"], rain=corrected_rainChance
        )
    # obj.save()  --> you don't need to save the obj again.
    context = {'context': obj}
    print(context)

这篇关于如何保存在数据库中的Django模型的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆