Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django method update_or_create troubles to increment value

Tags:

python

django

I've got a Django models:

class Item_received_log(models.Model):
   name = models.CharField(max_length=250)
   quantity = models.FloatField(default=1)

class Inventory (models.Model):
   name = models.CharField(max_length=250)
   quantity = models.FloatField(default=1)

I would like to update Inventory.quantity each time new item to Item_received_log is posted with matching name. I am not sure if it is right but I've decided to override save method of Item_received_log class so it updates Inventory list upon saving:

def save(self, *args, **kwargs):
    obj, created = Inventory.objects.update_or_create(
             name=self.name,
             defaults = {'quantity':(quantity + self.quantity)})
    super(Item_received_log, self).save(*args, **kwargs)

And in returns: NameError at /admin/accountable_persons/item_received_log/17/change/ global name 'quantity' is not defined

How can I resolve my issue or come up with better solution?

like image 241
webcosta Avatar asked Oct 16 '25 07:10

webcosta


1 Answers

Would have been a lot easier if we could simply throw in an F() expression into the default part of update_or_create to do all the magic, but the issue requesting this feature is still open.

You can, however, use a more verbose approach for now:

from django.db.models import F

def save(self, *args, **kwargs):
    obj, created = Inventory.objects.get_or_create(name=self.name)
    obj.quantity = F('quantity') + self.quantity
    obj.save()
    super(Item_received_log, self).save(*args, **kwargs)
like image 98
Moses Koledoye Avatar answered Oct 17 '25 21:10

Moses Koledoye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!