我正在尝试根据外来的其他字段选择设置字段默认值.
基本上,这些是类:
基本上,这些是类:
- 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')
每个“产品”都有默认价格(或建议价格),因此当用户在管理页面中想要添加新的销售并且他/她选择产品时,我需要动态地从Product.price复制到Sell.price建议的价格.
我不能使用“保存”方法,因为用户可以在那一刻进行更改.
是否有必要明确使用JavaScript?或者Django有一种优雅的方式来做到这一点吗?
解决方法
您可以使用预保存挂钩或通过覆盖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)