2012-03-22 58 views
0

我有以下型號:如何根據Django中選定的外鍵獲取模型字段值?

class OrderDetails(models.Model): 
OrderID = models.ForeignKey(Orders) 
Product = models.ForeignKey('SystemSetup.Products', unique=False) 
Quantity = models.DecimalField('Quantity', max_digits=18, decimal_places=0, default=1) 
Price = models.DecimalField('Price', max_digits=18, decimal_places=2) 

def __unicode__(self): 
return "%s" % (self.OrderID) 

我想要得到的Price價值,但必須取決於所選擇的Product

我也用內聯的admin:

class OrderInlines(admin.TabularInline): 
model = OrderDetails 
extra = 1 
readonly_fields = ['Price'] 

class OrdersAdmin(admin.ModelAdmin): 
fieldsets = [ 
('Order by:', {'fields': ['CustomerID']}), 
('Detailes', {'fields': ['CashierID', 'OrderDate']}), 
] 
list_display = ('OrderID', 'CashierID', 'CustomerID', 'OrderDate') 
list_filter = ['OrderID', 'CashierID', 'CustomerID', 'OrderDate'] 
search_fields = ['OrderID', 'CashierID__EmployeeName', 'CustomerID__CustomerName', 'OrderDate'] 
inlines = [OrderInlines] 

如何計算總價格(quantity * price)

回答

0

您可以通過重寫你的模型做這個的保存方法是這樣的:

class OrderDetails(models.Model): 
    OrderID = models.ForeignKey(Orders) 
    Product = models.ForeignKey('SystemSetup.Products', unique=False) 
    Quantity = models.DecimalField('Quantity', max_digits=18, decimal_places=0, default=1) 
    Price = models.DecimalField('Price', max_digits=18, decimal_places=2) 

    def save(self, *args, **kwargs): 
     self.Price = self.Product.Price * self.Quantity 

     super(OrderDetails, self).save(*args, **kwargs) 
相關問題