Vaibhav
Vaibhav

Reputation: 602

Saving and Updating data in Django

I have a form. The form has many text fields and those text fields hold some data that is stored in the database. This means that every time that form is opened, all the fields have the previous data.

In the form, a user can edit the old text fields, create new text fields and delete the existing text fields. When the form submits, all the data in the form is saved to the database. As of now, to save the data to the database, I'm first deleting the old data and then saving the new data to the database. I know that this approach is not optimal because deleting all the data for a minor change and then saving the whole data again doesn't make any sense.

Possible events

  1. User might edit some existing fields
  2. User might create some new fields
  3. User might delete some existing fields
  4. User might not make any changes and still submit the form

So, how can I handle the saving efficiently?

Model

from django.db import models
from django.contrib.auth.models import User

class Sentence(models.Model):
    user = models.ForeignKey(User, on_delete = models.CASCADE)
    sentence = models.CharField(max_length = 250)

Current Solution -

from .models import Sentence

def index(request):
    if request.method == "POST" and request.user.is_authenticated:
        Sentence.objects.filter(user = request.user).delete() # Deleting all the old data
        sentences = request.POST.getlist("sentence")
        
        for sentence in sentences:
            s = Sentence(
                user = request.user,
                sentence = sentence
            )
            s.save() # Saving data

    # Some more code

Upvotes: 0

Views: 1562

Answers (1)

Guillaume
Guillaume

Reputation: 2006

I am not sure to understand to fully understand the delete part but if you want to restart from 0 and create new sentences that's the only solution I see. However, for the creation part, there is a much more efficient solution using bulk_create (doc) :

def index(request):
    if request.method == "POST" and request.user.is_authenticated:
        Sentence.objects.filter(user = request.user).delete() # Deleting all the old data
        sentences = request.POST.getlist("sentence")
        
        sentences = list(map(
                lambda x: Sentence(user=request.user, sentence=x),
                sentences
            ))
        Sentence.objects.bulk_create(sentences)
        # the rest of your code...        

The advantage is that bulk_create will hit the database just once. It's really uncommon to iterate in Django while performing DB operations.

Upvotes: 1

Related Questions