Django Query Cache - same Data after DB Update until restarting Server

Hey there,
i have the following Problem with Django:
I am using row Queries with the connection module. Now i faced the Problem that after updating my Database, i still get the same Data until i restart the Django Server. I tried to use after every Query Select cursor.close(), but i did not work.
I think there must be a Cache in Django, which i have to disable. Do anyone know how i can solve this?

You’re going to need to post the code here that is involved. There are too many reasons why this might be happening for us to guess at the reasons.

(The most likely reason is that you’ve got your query code in the wrong location - but again, we’ll need to see the code.)

Note, when posting code here, enclose each block of code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted, which is critical with Python. (Do not post screenshots or images of code.)

Thanks for your reply.

This is my Code:

    if request.method == 'POST':
        datum = request.POST['datum_import']
        daten = []

        today = datetime.now()
        today = today.strftime("%d%m%Y_%H%M%S")

        if datum not in("", None):
            datum = datum.replace('-', '')
        else:
            messages.error(request, "Fehler im Datum.")
            return redirect('protokolle')


        cursor = connection.cursor()
        sql = f"SELECT * FROM daten WHERE s49 = 'BEREIT' AND tabelle = 'pr_entnahmestelle' AND SUBSTRING(letzteaenderung, 1, 8) = '{datum}' ORDER BY s25"
        cursor.execute(sql)
        result = dictfetchall(cursor)

        dict_protokolle = {}
        list_probest_nr = []
        list_probest_del = []


        ### --- Save data in variables --- ###
        for x in result:
            kunde = x['s2']
            ort = x['s9']
            strasse = x['s13']
            hausnummer = x['s14']
            my_id = x['s25']
            prob_stelle_nr = x['s28']
            auftr_nr = x['s29']
            mietername = x['s38']
            prob_datum = x['s40']
            prob_zeit = x['s41']
            proben_irn = x['s42']
            prob_entnommen = x['s44']
            entn_raum = x['s50']
            entn_armatur = x['s51']
            wt_entn = x['s53']
            wt_konst_zeit = x['s54']
            wt_konst = x['s55']
            wassertruebheit = x['s56']
            leerstand = x['s69']
            bemerkungen = x['s86']
            ausgewichen = x['s95']
            neuer_mieter = x['s107']
            tabelle = x['tabelle']

            dict_probestelle = {
                'my_id': my_id,
                'kunde': kunde,
                'hausnummer': hausnummer,
                'strasse': strasse,
                'ort': ort,
                'prob_datum': prob_datum,
                'prob_zeit': prob_zeit,
                'entn_raum': entn_raum,
                'entn_armatur': entn_armatur,
                'wt_entn': wt_entn,
                'wt_konst': wt_konst,
                'wt_konst_zeit': wt_konst_zeit,
                'wassertruebheit': wassertruebheit,
                'prob_entnommen': prob_entnommen,
                'auftr_nr': auftr_nr,
                'leerstand': leerstand,
                'neuer_mieter': neuer_mieter,
                'ausgewichen': ausgewichen,
                'mietername': mietername,
                'prob_stelle_nr': prob_stelle_nr,
                'tabelle': tabelle,
                'bemerkungen': bemerkungen,
                'proben_irn': proben_irn,
            }
            list_probest_nr.append(prob_stelle_nr)

            if my_id in dict_protokolle:
                dict_protokolle[my_id].append(dict_probestelle)
            else:
                dict_protokolle[my_id] = []
                dict_protokolle[my_id].append(dict_probestelle)


        ### --- verifying data  --- ###
        for my_id in dict_protokolle:
            json_obj = fd.pruefung(dict_protokolle[my_id])

        df = pd.DataFrame(columns=['Kunde','Straße', 'Hausnr', 'WACO ID', 'Probestelle', 'Problem'])

        for my_id in json_obj:
            i = 0
            for probestellen in json_obj[my_id]:
                for probestelle in probestellen:
                    list_probest_del.append(probestelle)
                    for problem in json_obj[my_id][i][probestelle]:
                        df = df.append({'Kunde':problem[1],'Straße':problem[2], 'Hausnr':problem[3], 'ID':my_id, 'Probestelle':probestelle, 'Problem':problem[0]}, ignore_index=True)
                    i+=1    
        list_probest_del = set(list_probest_del)

        #Probestellen will be cleaned up so that i have only the probestellen-items, which are clean without errors
        for item in list_probest_del:
            list_probest_nr.remove(item)

        try:
            sql_probestellen = ""
            for probestelle in list_probest_nr:
                sql_probestellen += f"'{probestelle}',"
            sql_probestellen = sql_probestellen[:-1]
            sql = f"UPDATE daten set s49='BEFUND_FEHLT', l6='update_digiwac' WHERE s49 = 'BEREIT' AND tabelle = 'pr_entnahmestelle' AND s28 IN({sql_probestellen}) ORDER BY s25"
            cursor.execute(sql)
            messages.success(request, "Statusupdate auf BEFUND_FEHLT erfolgreich.")
        except:
           messages.error(request, "Statusupdate auf BEFUND_FEHLT nicht erfolgreich.")

        cursor.close()
        list_probest_del = ""
        return redirect('protokolle')```

You show the first line as:

What is above this line in this view? Is it only the def ... line or was there more?

This is a part of a view for updating the data, but you’re asking about a view not showing the updated data. What is that view?

Above this line is only the def line, so this code snippet is the whole view. The View, which is Exporting Updated Data is the following:

def createPlausi(request):
    today = datetime.now()
    today = today.strftime("%d%m%Y_%H%M%S")

    datum_import = request.POST['datum_import']
    datum_import = datum_import.replace('-', '')

    cursor = connection.cursor()
    sql = "SELECT * FROM daten WHERE s49 = 'BEREIT' AND tabelle = 'pr_entnahmestelle' ORDER BY s25"
    cursor.execute(sql)
    anlagen = fct.dictfetchall(cursor)

    if len(anlagen) == 0:
        messages.error(request, "Keine Protokolle mit dem eingegebenen Importdatum vorhanden.")
        return redirect('protokolle')

    dict_protokolle = {}
    list_probest_nr = []
    list_probest_del = []


    ### --- Save data in variables --- ###
    for x in anlagen:
        kunde = x['s2']
        ort = x['s9']
        strasse = x['s13']
        hausnummer = x['s14']
        waco_id = x['s25']
        prob_stelle_nr = x['s28']
        auftr_nr = x['s29']
        mietername = x['s38']
        prob_datum = x['s40']
        prob_zeit = x['s41']
        proben_irn = x['s42']
        prob_entnommen = x['s44']
        entn_raum = x['s50']
        entn_armatur = x['s51']
        wt_entn = x['s53']
        wt_konst_zeit = x['s54']
        wt_konst = x['s55']
        wassertruebheit = x['s56']
        leerstand = x['s69']
        bemerkungen = x['s86']
        ausgewichen = x['s95']
        neuer_mieter = x['s107']
        tabelle = x['tabelle']

        dict_probestelle = {
            'waco_id': waco_id,
            'kunde': kunde,
            'hausnummer': hausnummer,
            'strasse': strasse,
            'ort': ort,
            'prob_datum': prob_datum,
            'prob_zeit': prob_zeit,
            'entn_raum': entn_raum,
            'entn_armatur': entn_armatur,
            'wt_entn': wt_entn,
            'wt_konst': wt_konst,
            'wt_konst_zeit': wt_konst_zeit,
            'wassertruebheit': wassertruebheit,
            'prob_entnommen': prob_entnommen,
            'auftr_nr': auftr_nr,
            'leerstand': leerstand,
            'neuer_mieter': neuer_mieter,
            'ausgewichen': ausgewichen,
            'mietername': mietername,
            'prob_stelle_nr': prob_stelle_nr,
            'tabelle': tabelle,
            'bemerkungen': bemerkungen,
            'proben_irn': proben_irn,
        }
        list_probest_nr.append(prob_stelle_nr)


        if waco_id in dict_protokolle:
            dict_protokolle[waco_id].append(dict_probestelle)
        else:
            dict_protokolle[waco_id] = []
            dict_protokolle[waco_id].append(dict_probestelle)

    ### --- verifying Data --- ###
    for waco_id in dict_protokolle:
        json_obj = fd.pruefung(dict_protokolle[waco_id])

    df = pd.DataFrame(columns=['Kunde','Straße', 'Hausnr', 'Ort', 'WACO ID', 'Probestelle', 'Probenehmer IRN', 'Problem'])

    for waco_id in json_obj:
        i = 0
        for probestellen in json_obj[waco_id]:
            for probestelle in probestellen:
                list_probest_del.append(probestelle)
                for problem in json_obj[waco_id][i][probestelle]:
                    df = df.append({'Kunde':problem[1],'Straße':problem[2], 'Hausnr':problem[4], 'Ort':problem[3], 'WACO ID':waco_id, 'Probestelle':probestelle, 'Probenehmer IRN':problem[5], 'Problem':problem[0]}, ignore_index=True)
                i+=1  
    list_probest_del = set(list_probest_del)

    #Probestellen will be cleaned up so that there are only datasets with plausibility errors
    for item in list_probest_del:
        list_probest_nr.remove(item)

    try:
        df.to_excel(r"W:\02_Abwicklung\0204_Doku\plausi_" + today + ".xlsx", index=False)
        messages.success(request, "Data exported")

    except:
        messages.error(request, "Error in the Plausi-Function. Please contact the Admin.")
    cursor.close()
    list_probest_del = ""
    return redirect('protokolle')

In this view, the plausibility errors will be exportet as an Excel-Sheet. First, this View i called. After seeing the plausibility errors, the “clean” Datasets will be updated, so the status is changed to BEFUND_FEHLT. After that, this view above will be called again. This time, the datasets, which are updated shouldnt be appear. But they do.
I debugged the whole code and i realized, that the data is updated successfully. Only after restarting the server, tha updated data is recognized by my program.

So it’s the view that is supposed to be showing the updated data that we need to see.

Yes, that’s right. But it does not display the data in the browser, it is exporting it as an excel sheet
(“Yes, that’s right.” was too short as an answer, that’s why i repeated the Export)

Still it’s the same question. What is the view that is retrieving the data and presenting it as a file to the browser?

It is the second view…

I don’t see anything in that view that is returning anything to the browser. I see a redirect to another url.

Maybe I’m just not understanding what you’re trying to describe here as the issue.

It is this code that I need to see.

Is this the code that you are saying is always returning the same data between restarts?

If so, what is this fct object?