i'm trying to create new object if not exists and update some fields if it exists , i've seen several answers but still its unclear , and i couldnt implement it well this is my models.py
class Information(models.Model):
name = models.CharField(max_length=50,unique=True)
def __str__(self):
return self.name
class Item(models.Model):
item = models.ForeignKey(Information,on_delete=models.CASCADE)
quantity = models.IntegerField()
quantity_storage = models.IntegerField(blank=True)
buying_price = models.DecimalField(max_digits=30,decimal_places=3)
def __str__(self):
return self.item.name
def save(self,*args,**kwargs):
if self.item:
Item.objects.filter(item__name=self.item).update(
quantity=F('quantity') + self.quantity
else:
super(Item,self).save(*args,**kwargs)
i have to update quantity field if the object already exists for example i've entered item :cableXYZ , quantity : 10 then i enter cableXYZ again with quantity : 20 it should update the quantity field to 30this works fine , but when i try to enter a new object which doesnt exists , it wont save the object !
is there something i've missed to add to save save() method ?! or isnt there a better approach to achieve it please ?!
i very appreciate your helps