'How to save data of the updated table to another table in Django

I just started in Django, I'm developing a web-application that want to create a Purchase Order and Masterlist. I started using the generic views and now I can create and update a Purchase Order. It has a status field of Pending and Received. If I created a new Purchase Order the default status is Pending and If I updated it to Received it should also save the data to Masterlist table. The thing is, it doesn't work. By the way, the received item should stay in Purchase Order table for history.

Since I'm using the generic views in Django.. I tried to put the masterlist table in the update view of the purchaseorder but It has error saying No masterlist found matching the query

Here is my class for the UpdateView

class PurchaseOrderUpdateView(LoginRequiredMixin, UpdateView):
    model = PurchaseOrder
    model = Masterlist
    fields = ['item_no', 'description', 'dimension', 'unit', 'quantity', 'cost', 'project_site', 'po_date', 'supplier', 'status']

    def form_valid(self, form):
        form.instance.prepared_by = self.request.user
        return super().form_valid(form)

What I expect is, when I update the status field of my Purchase Order to received, it should also saved the data of it to Masterlist. Or If the item in Purchase Order exists in Masterlist it will update the quantity on it.



Solution 1:[1]

Editing The Other table from the changes of the other table. hello I think you can use the models save() function to do that. If you have two tables A and B and you want when you update one the atribute of the other changes, So long as the tables relate lets try like these.

class B(models.Model):
    atribute_2 = models.CharField(max_length=255,null=True,blank=True)
class A(models.Model):
    atribute_1 = models.ForeignKey(B,on_delete=models.CASCADE,null=True,blank=True)
    atribute_3 = models.CharField(max_length=255,null=True,blank=True)

    def save(self, *args, **kwargs):
        if self.atribute_1 == "pending":
           self.atribute_1.atribute2 = "Pending"        
        super(A, self).save(*args, **kwargs)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Developer-Felix