Skip to content Skip to sidebar Skip to footer

How To Save Data In The Db Django Model?

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

Solution 1:

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)

Solution 2:

I would say you first should clean your code. It's not looking modular at all really. You should divide the endpoint view into a modular functions, so that it will become much easier to read. You're mixing the camelCase and under_score style in your variable naming, which is regarded as bad style.

After you have done this, you are ready to move on to the actual problem :). For that, I want you to get familiar with The python debugger. With that you can easily debug python code. Oldschool way would be to insert prints in your code, but that is usually slow, unless you smell where the problem could be.

Post a Comment for "How To Save Data In The Db Django Model?"