简体   繁体   English

django中如何根据其他字段动态设置字段值

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

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

Admin Panel Output管理面板 Output

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用其他字段的值在 Django 模型中创建一个字段? - How to create a field in django model using values of other fields? 如何基于其他字段提取csv文件中一个字段的值? - How to extract values of one field of csv file based on other fields? Django:根据其他字段更新字段值 - Django: Update Field Value Based on Other Fields 如何使用基于 python 中的其他字段的循环动态填充字段? - How do I make a field dynamically populated using a loop based on other fields in python? Django根据表单集中的其他两个字段计算字段 - Django calculate field based on two other fields in formset 在Django中,根据模型中的其他字段删除选项字段中的选项 - In Django, remove options in a choice-field based on other fields in a model 如何在Django中基于模型的其他字段的状态来修改字段渲染行为 - How to modify field rendering behaviour based on state of other fields of model in django Django Admin根据其他选择动态禁用字段 - Django Admin disable field dynamically based on other selections 如何基于同一模型中其他字段的值设置Django模型字段值 - How to set django model field value based-on value of other field in the same Model Django ORM:获取一个字段的最大值与对应的其他字段值 - Django ORM: Get maximum value of a field with corresponding other fields values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM