如何根据Django中选定的外键获取模型字段值?

时间:2012-03-22 11:01:35

标签: django django-models django-admin

我有以下型号:

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中使用InLines:

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)

1 个答案:

答案 0 :(得分: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)