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

前端之家收集整理的这篇文章主要介绍了javascript – Django根据其他字段动态设置字段值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试根据外来的其他字段选择设置字段默认值.
基本上,这些是类:
  1. class Product(models.Model):
  2. description = models.CharField('Description',max_length=200)
  3. price = models.FloatField('Price')
  4.  
  5. class Sell(models.Model):
  6. product = models.ForeignKey(Product)
  7. price = models.FloatField('Price')

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

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

解决方法

您可以使用预保存挂钩或通过覆盖Sell模型的save()方法解决此问题.
  1. from django.db import models
  2.  
  3. class Product(models.Model):
  4. description = models.CharField('Description',max_length=200)
  5. price = models.FloatField('Price')
  6.  
  7. class Sell(models.Model):
  8. product = models.ForeignKey(Product)
  9. price = models.FloatField('Price')
  10.  
  11. # One way to do it:
  12. from django.db.models.signals import post_save
  13. def default_subject(sender,instance,using):
  14. instance.price = instance.product.price
  15. pre_save.connect(default_subject,sender=Sell)
  16.  
  17. # Another way to do it:
  18. def save(self,*args,**kwargs):
  19. self.price = self.product.price
  20. super(Sell,self).save(*args,**kwargs)

猜你在找的JavaScript相关文章