![](/img/trans.png)
[英]How to create a field in django model using values of other fields?
[英]How to set field values dynamically based on other fields 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)
我想將 Product.price 值動態復制到 Sell.price 並將其設置為默認值。 用戶可以稍后更改 Sell.price 值。 我為此目的實現了 save() 方法,但它沒有顯示任何值。 怎么做?
是的,您的方法很好,只需要像這樣更改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.