【问题标题】:how to save data in the db django model?如何在 db django 模型中保存数据?
【发布时间】:2016-06-13 00:35:15
【问题描述】:

美好的一天,我真的不明白我在这里做错了什么。我正在使用这个函数基础视图将我的废品数据与 django 模型一起存储在数据库中,但现在它不再保存了。我真的不明白为什么。有什么想法吗?

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]))

【问题讨论】:

  • 你到底做了什么改变? “它没有保存”是什么意思 - 你收到错误还是在数据库中找不到对象?
  • 另外,你能发布你的WeatherData类定义吗?
  • @ben432rew 我只能说我在我的数据库中看不到任何东西,当我打印上下文时它什么都没有

标签: python django django-models beautifulsoup


【解决方案1】:

您的try/except 块肯定有问题。有趣的代码在创建对象之前一直有效,您应该将该部分更改为:

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)

【讨论】:

  • 这也是这个方法没有解决的问题。它不保存
  • 这种情况下context的输出是什么?
  • 没什么,它甚至没有打印出来。但是我现在通过这样做来保存它 rainChance = 0 Correct_rainChance = rainChance obj = WeatherData.objects.get_or_create( min_temp=forecast["LowTemp"], high_temp=forecast["HighTemp"], date=forecast["Date"], wind_speed=forecast["WindSpeed"], rain=corrected_rainChance) context = {'context': obj} return render(request, 'forecastApp/pages/fetch_weather.html', context)
  • 好吧,如果在这种情况下没有打印,则不会评估 else 块。所以forecast["Rainfall"] == '*'True
  • 不,我刚刚删除了 else 部分,现在它不为空,但有时它可能会为空
【解决方案2】:

我会说你首先应该清理你的代码。它看起来根本不是模块化的。您应该将端点视图划分为模块化功能,这样它就会变得更容易阅读。您在变量命名中混合了 camelCase 和 under_score 样式,这被认为是不好的样式。

完成此操作后,您就可以着手解决实际问题了:)。为此,我希望您熟悉The python debugger。有了它,您可以轻松调试 python 代码。老派的方法是在你的代码中插入打印,但这通常很慢,除非你闻到问题可能出在哪里。

【讨论】:

  • 不知道是不是真的不一样但是我用django-debug-toolbar来调试
猜你喜欢
  • 2021-12-17
  • 2022-08-20
  • 2019-10-12
  • 1970-01-01
  • 1970-01-01
  • 2013-05-16
  • 2023-03-23
  • 1970-01-01
  • 2019-01-19
相关资源
最近更新 更多