Heenashree Khandelwal
Heenashree Khandelwal

Reputation: 689

Need a calculated value in models in Django

I want a calculated value in models.py. Below is the file models.py. I manage to get the price as expected but the price doesn't appear as one of the field. What I mean is, when I enter delivery_price and support_price, the price field should be calculated and be shown in the below page itself (attached image). Is this possible or am I getting something wrong?

delivery_price = models.DecimalField(max_digits=10, decimal_places=0,default=0)
support_price = models.DecimalField(max_digits=10, decimal_places=0,default=0)

#def get_price(self):
#    "Returns the price."
#    return (self.delivery_price + self.support_price)
#price = property(get_price)

price = models.DecimalField(max_digits=10, decimal_places=0,editable=False)

def save(self, *args, **kwargs):
    self.price = self.delivery_price + self.support_price
    super(Product, self).save(*args, **kwargs)

enter image description here

Upvotes: 0

Views: 75

Answers (1)

Sandeep Balagopal
Sandeep Balagopal

Reputation: 1983

editable=False means the field won't show up in Django admin. Instead in your admin.py ModelAdmin make it a read only field.

class MyModelAdmin(admin.ModelAdmin):
    model = MyModel
    readonly_fields = ('price',)

admin.site.register(MyModel, MyModelAdmin)

Upvotes: 2

Related Questions