(CRUD) Inventory System with Sub-inventories in DJANGO

27 Views Asked by At

This CRUD is basically a Main Inventory(a), which is going to be used by the inventory manager to feed workers inventories(b,c,d..)... When I try to transfer an item from A to B, the item gets transferred successfully, however, if item already exists, it still creates a new one, duplicating the Item several times.

For Example:

If a subinventory has "2 Screws", I add "3 Screws".

Now the Subinventory has "2 Screws, and "3 Screws", instead of having now "5 Screws".

The Models:

Main Inventory

class Articulo(models.Model):
    id = models.AutoField(primary_key=True)
    nombre = models.CharField(max_length=50)
    descripcion = models.CharField(max_length=100, null=True)
    costo = models.IntegerField(null=True)
    cantidad = models.IntegerField(null=True)
    medida = models.CharField(max_length=20)
    fecha_ingreso = models.DateTimeField(auto_now_add=True, null=True)
    fecha_salida = models.DateTimeField(auto_now_add=True, null=True)
    ubicacion = models.CharField(max_length=50, default='Almacen')
    

SubItem and Subinventory

class articuloInventario(models.Model):
    articulo = models.CharField(max_length=50, null=True)
    cantidad = models.IntegerField(null=True)
    medida = models.CharField(max_length=20, null=True)
    fecha_ingreso = models.DateTimeField(auto_now_add=True, null=True)
    ubicacion = models.IntegerField(null=True)

class brigadaInventario(models.Model):
    id = models.AutoField(primary_key=True)
    articulos = models.ManyToManyField(articuloInventario)

Views:

def transferir_articulo(item_id, quantity):
    item_a = get_object_or_404(Articulo, id=item_id, cantidad__gte=quantity)
    item_b = get_object_or_404(articuloInventario, id=item_id, cantidad__gte=quantity)
    inventario = articuloInventario.objects.all()
    
    
    for b in inventario:
        if item_a.nombre == b.articulo:
            item_a.cantidad -= quantity
            item_a.save()
            b.cantidad += quantity
            b.save()
            return JsonResponse({'mensaje': f'{quantity} items transferred from inventory A to inventory B.'})
    item_a.cantidad -= quantity
    item_a.save()
    item_b.cantidad += quantity
    item_b.save()
    return JsonResponse({'mensaje': f'{quantity} items transferred from inventory A to inventory B.'})

Any suggestion on how could I prevent this code from creating record over record? If the Item that is going to be transferred exists, just to add quantity to this item and subtract from main inventory

0

There are 0 best solutions below