1

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

1
  • if self.item will always be True if I'm not mistaken. Do you want to create() an object and update it if it is already in the database? Commented May 25, 2021 at 22:29

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.