Django根据其他字段动态设置字段值

Tav*_*avo 7 javascript django autocomplete django-forms django-admin

我正在尝试根据外来的其他字段选择设置字段默认值.基本上,这些是类:

class Product(models.Model):
        description = models.CharField('Description', max_length=200)
        price = models.FloatField('Price')

class Sell(models.Model):
        product = models.ForeignKey(Product)
        price = models.FloatField('Price')
Run Code Online (Sandbox Code Playgroud)

每个"产品"都有默认价格(或建议价格),因此当用户在管理页面中想要添加新的销售并且他/她选择产品时,我需要动态地从Product.price复制到Sell.price建议的价格.我不能使用"保存"方法,因为用户可以在那一刻进行更改.

是否有必要明确使用JavaScript?或者Django有一种优雅的方式吗?

Mar*_*som 3

您可以使用预保存挂钩或覆盖 Sell 模型的 save() 方法来解决此问题。

from django.db import models

class Product(models.Model):
    description = models.CharField('Description', max_length=200)
    price = models.FloatField('Price')

class Sell(models.Model):
    product = models.ForeignKey(Product)
    price = models.FloatField('Price')

    # One way to do it:
    from django.db.models.signals import post_save
    def default_subject(sender, instance, using):
        instance.price = instance.product.price
    pre_save.connect(default_subject, sender=Sell)

    # Another way to do it:
    def save(self, *args, **kwargs):
        self.price = self.product.price
        super(Sell, self).save(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)