Django:根据其他字段更新字段值

1 投票
2 回答
2721 浏览
提问于 2025-04-16 03:18

我不太确定在不修改管理界面的情况下,这个是否可行。

我有一个叫“Quote”的模型,它可以包含多个“Product”模型。我通过一个中间模型“QuoteIncludes”将这两者连接起来。现在这三个模型的结构是这样的:

class Product(models.Model):
    name = models.CharField(max_length=100)
    short_desc = models.CharField(max_length=200)
    default_cost = models.DecimalField(max_digits=15, decimal_places=2)
    default_price = models.DecimalField(max_digits=15, decimal_places=2)
    shipping_per_unit = models.DecimalField(max_digits=9, decimal_places=2)
    weight_in_lbs = models.DecimalField(max_digits=5, decimal_places=2)

    def __unicode__(self):
        return self.name

class Quote(models.Model):

    ## Human name for easy reference
    name = models.CharField(max_length=100)
    items = models.ManyToManyField(Product, through='QuoteIncludes')

    def __unicode__(self):
        return self.name

class QuoteIncludes(models.Model):

    ## Attach foreign keys between a Quote and Product
    product = models.ForeignKey(Product)
    quote = models.ForeignKey(Quote)

    ## Additional fields when adding product to a Quote
    quantity = models.PositiveIntegerField()
    per_unit_cost = models.DecimalField(max_digits=15, decimal_places=2)
    per_unit_price = models.DecimalField(max_digits=15, decimal_places=2)

    def _get_extended_price(self):
        """Gets extended price by multiplying quantity and unit price."""
        if self.quantity and self.per_unit_price:
            return self.quantity * self.per_unit_price
        else:
            return 0.00

    extended_price = _get_extended_price

我希望能在管理界面创建一个Quote,当我填写了每个项目的数量和单价后,按一下Tab键,它能自动计算出“extended_price”,也就是数量和单价的乘积。我觉得这可能需要加一些AJAX代码。

我想要的功能的注释图片

2 个回答

0

你很难在那个更改列表中找到这个字段,因为它属于一个和正在编辑的模型不同的模型。不过,你可以把相关的模型作为内嵌模型放在这个模型下面。然后,你可以写一些JavaScript代码,把你输入的两个字段的值结合起来,生成你想要的输出值,并把它放到内嵌模型的合适字段里。

或者,你可以写一个自定义的视图,不依赖于管理员界面;)

3

关于如何在你的模型管理中包含JavaScript的信息:

点击这里查看详细文档

例如:

class Media:
    js = (
        'http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js',
        '/media/js/calculate.js',
    )

你的脚本可能看起来像这样:

function currencyFormat(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    }
    return x1 + x2;
}

jQuery(document).ready(function($){
    $('input[id$=quantity], input[id$=per_unit_cost]').live('keyup', function() {
        var $tr = $(this).parents('tr');
        var quantity = parseInt($tr.find('input[id$=quantity]').val());
        var count = parseInt($tr.find('input[id$=per_unit_cost]').val());

        if(quantity && count) {
            $tr.find('input[id$=per_unit_price]').html(currencyFormat(quantity * count));
        }
    });
});

我还添加了一个货币格式的函数,以防你想用它。

撰写回答