skip to Main Content

I am trying to update a record in Database using Django but it adds the same record again. How i can fix it? code is given below.

def update(request, id):
    book = tblbook.objects.get(id=id)
    form = tblbook(BookID = book.BookID, BookName=book.BookName, Genre=book.Genre,Price=book.Price) 
    form.save()
    return redirect("/show")

2

Answers


  1. your object is in book, as you have used get() method
    now should do something like this

    object_name.column_name = "Your value that you want to save"
    

    accotding to your snippet it would be like this

    book.BookID = "1"
    book.BookName = "Any book name"
    book.Genre = "Any genre"
    book.Price = "Price of the book"
    book.save()
    

    You can also use update() method with filter() method, and it would look something like this

    book = tblbook.objects.filter(id=id).update(BookID = "123", BookName="Any book name", Genre= "any genre", Price="price")
    
    Login or Signup to reply.
  2. Your code is inserting new record to DB.
    Suppose you want to update the book name, then below code might help-

    book = tblbook.objects.get(id=id)
     
    book.BookName = "some book name"
    
    book.save()
    

    similarly, you can update other fields as well

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search