Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

294
Vistas
Django method update_or_create troubles to increment value

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?

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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)
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda