我有两个模型,如下所示。
PRODUCT_TYPE=(('TL','Tubeless Tyre'), ('TT','Tubed Tyre'), ('NA','Not applicable'))
class Product(models.Model):
product_group=models.ForeignKey('productgroup.ProductGroup', null=False,blank=False)
manufacturer=models.ForeignKey(Manufacturer, null=False,blank=False)
product_type=models.CharField(max_length=2, choices=PRODUCT_TYPE,)
opening_stock=models.PositiveIntegerField(default=0)
def __str__(self):
return '%s (%s, %s, %s) o.stock = %d ' % (self.product_group, self.manufacturer, self.product_type ,self.opening_stock)
unique_together = ('product_group', 'manufacturer','product_type')
def get_total_stock_in(self):
return Stock.objects.filter(product=self.id,ttype='I').aggregate(Sum('quantity'))
def get_total_stock_out(self):
return Stock.objects.filter(product=self.id,ttype='O').aggregate(Sum('quantity'))
和
TRANSACTION_TYPE=(('I','Stock In'),('O','Stock Out'))
class Stock(models.Model):
product=models.ForeignKey('product.Product', blank=False,null=False)
date=models.DateField(blank=False, null=False,)
quantity=models.PositiveIntegerField(blank=False, null=False)
ttype=models.CharField(max_length=1,verbose_name="Ttransaction type",choices=TRANSACTION_TYPE, blank=False)
added_date=models.DateTimeField(blank=False, auto_now=True)
def get_absolute_url(self):
return reverse('product_detail', args=[str(self.product.id)])
def __str__(self):
return ('[%s] %s (%s) %d' %(self.product, self.date, self.ttype, self.quantity))
和视图为..
class ProductDetail(DetailView):
model=Product
def get_context_data(self, **kwargs):
context = super(ProductDetail, self).get_context_data(**kwargs)
product_id=self.kwargs['pk']
context['total_stock_in']=Stock.objects.filter(product=product_id,ttype='I').aggregate(Sum('quantity'))
context['total_stock_out']=Stock.objects.filter(product=product_id,ttype='O').aggregate(Sum('quantity'))
return context
这是我的模板。
Opening stock : {{object.opening_stock}}
<br>
Total Stock In: {{total_stock_in.quantity__sum}}
<br>
Total Stock Out: {{total_stock_out.quantity__sum}}
<br>
Balance stock : ???
现在,在模板product_detail.html
内,我需要将opens_stock + total_stock_in-total_stock_out的结果显示为当前余额。
感谢您的任何意见。
答案 0 :(得分:0)
我最终如下所示。
为模型添加了一种方法
class Product(models.Model):
...........
def get_balance_stock(self):
return (self.opening_stock+self.get_total_stock_in()['quantity__sum']
- self.get_total_stock_out()['quantity__sum'])
然后从模板中调用它
Balance stock: {{object.get_balance_stock}}