2017-06-16 57 views
0

之前驗證DB值(首先對不起的含糊的標題 - 我不知道該怎麼形容這個標題中的問題)Django的 - 保存形式

我有兩個型號爲如下。

PRODUCT_TYPE=(('TL','Tubeless Tyre'), ('TT','Tubed Tyre'), ('NA','Not applicable')) 
FRONT_BACK=(('F','Front'), ('B','Back'), ('C','Common')) 

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) balance = %d ' % (self.product_group, self.manufacturer, self.product_type ,self.get_balance_stock()) 

    class Meta: 
     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')) 
    def get_balance_stock(self): 
     return (self.opening_stock+self.get_total_stock_in()['quantity__sum'] 
       - self.get_total_stock_out()['quantity__sum']) 

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) 

我製作了一個模型表單和兩個單獨的視圖來記錄庫存和庫存,如下所示。

class StockInOutForm(forms.ModelForm): 
    class Meta: 
     model = Stock 
     fields=['product','quantity','date'] #'ttype', 
     widgets = { 
      'date': forms.DateInput(attrs={'class': 'datepicker'}), 
     } 

class StockIn(CreateView): 
    model=Stock 
    form_class=StockInOutForm 
    def get_context_data(self, **kwargs): 
     context = super(StockIn, self).get_context_data(**kwargs) 
     context['ttype']="Stock In" 
     return context 
    def form_valid(self, form): 
     stockin = form.save(commit=False) 
     stockin.ttype = 'I' 
     stockin.save() 
     return http.HttpResponseRedirect(reverse('stock_list')) 

class StockOut(CreateView): 
    model=Stock 
    form_class=StockInOutForm 
    def get_context_data(self, **kwargs): 
     context = super(StockOut, self).get_context_data(**kwargs) 
     context['ttype']="Stock Out" 
     return context 
    def form_valid(self, form): 
     stockout = form.save(commit=False) 
     stockout.ttype = 'O' 
     stockout.save() 
     return http.HttpResponseRedirect(reverse('stock_list')) 

現在如何防止數量大於可用庫存的庫存出庫操作?

我相信我可以從相應的產品對象調用方法get_balance_stock()並將該值與表中給出的當前quantity進行比較。

請詳細說明如何實施它。

謝謝。

回答

1

您應該在表單類上定義一個clean方法。您可能希望使用單獨的子類進行缺貨操作,因爲此驗證只適用於這些操作。

class StockOutForm(StockInOutForm): 
    def clean(self): 
     product = self.cleaned_data['product'] 
     available = product.get_balance_stock() 
     if self.cleaned_data['quantity'] > available: 
      raise forms.ValidationError("You can't take out more stock of {} than is available ({})".format(product, available) 
+0

哇!我從來沒有想過它會像這樣簡單。非常感謝。 – art06