In Django, I am trying to modify the title of the existing book with id. My views.py file consists of
b=Books.objects.filter(book_id__iexact=book)
b.title = "Narnia"
b.save()
I am getting error and unable to save the model instance.
CodePudding user response:
Try using get
method instead of filter
. When you use filter you are using a queryset object. Instead of using Books.objects.filter(book_id__iexact=book)
try using b=Books.objects.get(book_id__iexact=book)
CodePudding user response:
you can use 2 methods to update a record.
https://docs.djangoproject.com/en/4.0/ref/models/querysets/#update
.get will work for a single object and .filter will work for multiple records
#1st
b=Books.objects.get(book_id=book)
b.title = 'Foo'
b.save()
#2nd
Books.objects.filter(book_id__iexact=book).update(title='Foo')