Replacing an old table with a new one in the Django database?

Viewed 486

Hi I am working on a Django Project and added the functionality of importing a csv file to the Django database using the following code

class UploadFileForm(forms.Form):
    file = forms.FileField()


    def import_csv(request):
        if request.method == "POST":
            with open('C:/Users/admin/Desktop/Projekt/test2.csv') as file:
                reader = csv.reader(file)
                for column in reader:
                    p = CSV(gebäude=column[0], etage=column[1], raum=column[2], dose=column[3])
                    p.save()
                return redirect('upload:index')
        form = UploadFileForm()
        return render(
        request, "upload/csv_upload.html", {"form": form}
    )

However if i make changes to the csv file and add it to the database it just adds everything and I have the data basically twice in the table. I would like to know if there is any option to just replace the old data in the table with the changed data, instead of just adding it to the table. I use the standard sqlite3 database.

This is the csv file

25.41, 1, 21, 10
25.42, 2, 22, 14
25.43, 1, 23, 13
25.44, 3, 24, 12
25.45, 2, 25, 11
25.46, 0, 15, 23

This is my models.py

class CSV(models.Model):
    gebäude = models.CharField(max_length=100)
    etage = models.CharField(max_length=100)
    raum = models.CharField(max_length=100)
    dose = models.CharField(max_length=100)

And my Html form

<h2>Upload CSV</h2>

<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>

Any help would be appreciated

1 Answers

You can just do CSV.objects.all().delete() to empty the existing table.

Related