artiest
artiest

Reputation: 592

how to update(calculate) a specific field if the object exists django

i made a project for a store , and i want to prevent from duplicate products , if the product doesnt exists then insert it into the database , but otherwise if it doesn't then just update field(quantity)

models.py

class Item(models.Model):
    item = models.ForeignKey(Product,on_delete=models.CASCADE)
    quantity = models.IntegerField()

for example we have inserted this data:

 item = mouse , quantity = 20 

then we add this data later

 item = mouse , quantity = 30

now what i try to whenever the item exists , just update the quantity like this (20 + 30 ) = 50 , add the previous quantity with new quantity to get total number of quantities ! is it possible please ? i've read some articles about get_or_create and update_or_create but still i dont have any idea how it work in my case !?

views.py

def createNewProduct(request):
   form = ItemForm()
   if request.method == 'POST':
       form = ItemForm(request.POST)
       if form.is_valid():           
            form.save()

   return render(request,'temp/add_item.html',{'form':form})

forms.py

class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = ['item','quantity']

thank you for your suggestion regards ..

Upvotes: 0

Views: 1062

Answers (1)

Klim Bim
Klim Bim

Reputation: 646

First of all, you can use update_or_create. However, this method will override your current data if you do a PUT. Your quantity will be overriden and will not be like this quantity+=new_quantity.

Therefore, you must override save() in ItemForm doc

def save(self, *args, **kwargs):
    if self.instance is None
       # custom POST operation or `return super().save(*args, **kwargs)`
    else:   
       self.instance.quantity = self.instance.quantity + self.cleaned_data.get('quantity')
       # further PUT operation
       instance.save()
    ...

self.data and self.instance comes from BaseModelForm

Upvotes: 1

Related Questions