Home > Net >  Django - how to show a mathematic result as percentage in dango admin
Django - how to show a mathematic result as percentage in dango admin

Time:02-14

I have created a model that have one field that calculate the percentage of a month profit, the result is a float number rounded to 2 decimals, for example 0.50

I would like to have in the admin list as percentage, for example. 0.50 would show as 50.00%, is that possíble, how can i achieve that?

my model:

class PortfolioToken(models.Model):
    total_today = models.FloatField()
    order_value = models.FloatField()
    token_price = models.FloatField()
    month_profit = models.FloatField(editable=False)

    def save(self, *args, **kwargs):
        if PortfolioToken.objects.exists():
            last = PortfolioToken.objects.latest('id')
            # month profit would show as percentage in admin
            self.month_profit = round((self.token_price - last.token_price)/last.token_price, 2)
        else
        ...
            

My admin list

class PortfolioTokenAdmin(admin.ModelAdmin):
    list_display =('total_today', 'order_value', 'token_price', 'month_profit')

CodePudding user response:

You can add it as a custom field:

class PortfolioTokenAdmin(admin.ModelAdmin):
    fields = ('total_today', 'order_value', 'token_price', 'month_profit', 'percentage')
    readonly_fields = ('percentage',)

    def percentage(self, obj):
        # Return the month_profit as percentage string
        return str(format(float(obj.month_profit * 100), '.2f')   ' %')
  • Related