I am trying to update multiple row depends on multiple data. But while I submit, only one row update and got this error 'int' object has no attribute 'save'. I think the problem is in my view. My view are given bellow:
def saleForm(request):
stb = []
if request.method == 'POST':
for stb_array in request.POST.getlist('stb_sl'):
stb.append(stb_array)
i = 0
for stb_ho in stb:
stb_update = StpDetails.objects.filter(stp_sl=stb_ho).update(
sale_date=date,
sales_invoice=invoice,
status='Sold')
stb_update.save()
i = 1
messages.success(request, 'You have successfully save data.')
return render(request,'sale/invoice_details.html',{})
My Model:
class StpDetails(models.Model):
id = models.AutoField(primary_key=True)
entry_date = models.DateField(default=date.today)
stp_sl = models.CharField(max_length=50, unique=True)
stp_name = models.CharField(max_length=30)
sale_date = models.DateField(auto_now=False, null=True)
sales_invoice = models.CharField(max_length=20, blank=True)
install_date = models.DateField(auto_now=False, null=True)
installer = models.CharField(max_length=50, blank=True)
house = models.CharField(max_length=100, blank=True)
status = models.CharField(max_length=7, default='Unsold')
def __str__(self):
return self.stp_sl
CodePudding user response:
The docs on the method QuerySet.update()
show that this method already saves the changes, so there is no need to use .save()
afterwards.
Also, this method does NOT return an model instance, but an integer; that is why you are getting the error because stb_update
is an integer and does not have a method called .save()
.
update() [...] and returns the number of rows matched (which may not be equal to the number of rows updated if some rows already have the new value).
So your code could look like this:
def saleForm(request):
if request.method == 'POST':
date = ...
invoice = ...
stb = []
for stb_array in request.POST.getlist('stb_sl'):
stb.append(stb_array)
i = 0
for stb_ho in stb:
stb_update = StpDetails.objects.filter(stp_sl=stb_ho).update(
sale_date=date,
sales_invoice=invoice,
status='Sold')
i = 1
messages.success(request, 'You have successfully save data.')
else:
# a GET request
pass
return render(request, 'sale/invoice_details.html', {})