How to set field values dynamically based on other fields in django

Question:

I have two models in 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. User can change Sell.price value later. I have implemented save() method for this purpose, but it is not showing any value.
How to do it?

Asked By: Waleed Farrukh

||

Answers:

Yes, your approch is fine just need to change price = models.FloatField(blank=True,null=True) like this

models.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

enter image description here