韩昱邦
韩昱邦

Reputation: 31

How to get the current stock quantity for each item in an inventory system?

I wanna summarize the current stock quantity of each item in django admin. In item page, each item have a column, and I wanna show the number in each column of item. This is my model:

from django.contrib.auth.models import User
from django.db import models


class Item(models.Model):
    item_name = models.CharField(max_length=128)

class In(models.Model):
    in_date = models.DateTimeField()
    item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='ins')
    quantities = models.IntegerField()


class Out(models.Model):
    out_date = models.DateTimeField()
    item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='outs')
    quantities = models.IntegerField()

Model In means stock-in, Out means stock-out

I write functions in my admin.py like below:

class ItemAdmin(admin.ModelAdmin):
    list_display = ['item_name', 'pattern', 'vendor', 'item_ins', 'item_outs']

    def item_ins(self, obj):
        return obj.ins.aggregate(Sum('quantities')).get('quantities__sum')
    item_ins.short_description = 'stock-in'

    def item_outs(self, obj):
        return obj.outs.aggregate(Sum('quantities')).get('quantities__sum')
    item_outs.short_description = 'stock-out'

I already knew how to aggregate total stock-in/stock-out number of each item, but I don't know how to get current stock quantity(stock-in subtract sotck-out) of each item.

Please help me! Thank you!

Upvotes: 1

Views: 477

Answers (2)

韩昱邦
韩昱邦

Reputation: 31

    def item_quantity(self, obj):
    if not self.item_ins(obj):
        return '-'
    if self.item_outs(obj):
        return self.item_ins(obj) - self.item_outs(obj)
    return '-'

Thanks to Mr Dharanidhar Reddy , this is my final code . Sometimes stock-in or stock-out may be empty , so I added some if statement.

Upvotes: 1

Dharanidhar Reddy
Dharanidhar Reddy

Reputation: 878

The simplest but not so efficient implementation would be

def item_quantity(self, obj):
        return self.item_ins(obj)-self.item_outs(obj)

Upvotes: 1

Related Questions