如何在django中基于其他字段动态设置字段值

qkf9rpyu  于 2023-01-18  发布在  Go
关注(0)|答案(1)|浏览(181)

我在 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值。我为此实现了保存()方法,但它没有显示任何值。如何操作?

9lowa7mx

9lowa7mx1#

是的,您的方法很好,只需将price = models.FloatField(blank=True,null=True)更改为这样

www.example.commodels.py
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)
管理面板输出

相关问题