Home > OS >  Updating model field by adding old value to new Django
Updating model field by adding old value to new Django

Time:11-07

I'm trying to keep track of the total hours being put into a work order. I'd like to add the new number being entered to the number existing in the DB and return the total.

Thank you in advance for any help.

The Model:
class WorkOrder(models.Model):
    client = models.ForeignKey(Contact, on_delete=models.CASCADE)
    hours_worked = models.IntegerField()

The View:
class UpdateWorkOrder(LoginRequiredMixin, generic.UpdateView):
    model = WorkOrder
    template_name = 'client/update_workorder.html'
    success_url = reverse_lazy('dashboard')

CodePudding user response:

You can add this method to the view:

    def get_form_class(self):
        work_order = WorkOrder.objects.all().order_by('-id')[0] # Get the previous latest object here
        new_hours = work_order.hours_worked   self.object.hours_worked
        self.object.hours_worked = new_hours

OR

You can add the same code to pre save method to model.

  • Related