I have 2 DecimalFields in 1 model. How can I sum both fields together and have the total show up in the admin view?
price = models.DecimalField(max_digits=6, decimal_places=2)
spotters = models.DecimalField(max_digits=6, decimal_places=2, default=150)
There has to be a "container to retain the sum in admin view so I have:
total_price = models.DecimalField(max_digits=100, decimal_places=3, default=0)
at the end
then I finish with a return method:
def get_cost(self):
return self.price self.spotters
but its not working
CodePudding user response:
You can use the list display of ModelAdmin
as stated in the documentation.
class MyModel(models.Model):
...
def get_cost(self) -> int:
return self.price self.spotters
class MyModelAdmin(admin.ModelAdmin):
list_display = ['get_cost']
CodePudding user response:
I would advise to work with a property and without a total_price
, since that only introduces data duplication, so:
class MyModel(models.Model):
price = models.DecimalField(max_digits=6, decimal_places=2)
spotters = models.DecimalField(max_digits=6, decimal_places=2, default=150)
@property
def total_price(self):
return self.price self.spotter
In the ModelAdmin
, you can then add 'total_price'
in the readonly_fields
attribute [Django-doc]:
class MyModelAdmin(admin.ModelAdmin):
list_display = ('price', 'spotters', 'total_price')
fields = ('price', 'spotters')
readonly_fields = ('total_price',)
admin.site.register(MyModel, MyModelAdmin)