簡體   English   中英

django中如何根據其他字段動態設置字段值

[英]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)

模型.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)

管理面板 Output

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM