[英]How to set field values dynamically based on other fields in django
I have two models in Django.我在 Django 中有两个模型。
class Product(models.Model):
description = models.CharField('Description', max_length=200)
price = models.FloatField()
class Sell(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
price = models.FloatField()
def save(self, *args, **kwargs):
self.price = self.product.price
super(Sell, self).save(*args, **kwargs)
I want to copy dynamically Product.price value to Sell.price and set it as a default value.我想将 Product.price 值动态复制到 Sell.price 并将其设置为默认值。 User can change Sell.price value later.
用户可以稍后更改 Sell.price 值。 I have implemented save() method for this purpose, but it is not showing any value.
我为此目的实现了 save() 方法,但它没有显示任何值。 How to do it?
怎么做?
Yes, your approch is fine just need to change price = models.FloatField(blank=True,null=True)
like this是的,您的方法很好,只需要像这样更改
price = models.FloatField(blank=True,null=True)
class Product(models.Model):
description = models.CharField('Description', max_length=200)
price = models.FloatField()
def __str__(self):
return self.description
class Sell(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
price = models.FloatField(blank=True,null=True)
def save(self, *args, **kwargs):
self.price = self.product.price
super(Sell, self).save(*args, **kwargs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.