artiest
artiest

Reputation: 592

update object if exists and create if it not exists django

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

Upvotes: 1

Views: 2506

Answers (1)

TioneB
TioneB

Reputation: 468

I'm guessing you want to update all Item with the Information you're trying to create. I would do it like this:

def save(self,*args,**kwargs):
    items = Item.objects.filter(item=self.item)
    if items: # if some items are found in the database
        items.update(quantity=F('quantity') + self.quantity)
    else:
        return super(Item,self).save(*args,**kwargs)

Also, I find your naming scheme confusing, the model Item containing an ForeignKey Information called item is calling for trouble.

Upvotes: 1

Related Questions