How can I call model methods or properties from Django Admin?

Is there a natural way to display model methods or properties on a Django admin site? In my case, I have basic statistics for a symbol that is part of the model, but other things, such as status effects, that affect the overall calculation for this statistic:

class Character(models.Model):
    base_dexterity = models.IntegerField(default=0)

    @property
    def dexterity(stat_name):
          total = self.base_dexterity
          total += sum(s.dexterity for s in self.status.all()])
          return total

It would be nice if I could display the general calculated statistics with the field in order to change the basic statistics on the "Change Character" page, but it is not clear to me how to include this information in the page.

+3
source share
1 answer

Good example from docs :

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    color_code = models.CharField(max_length=6)

    def colored_name(self):
        return '<span style="color: #%s;">%s %s</span>' % (self.color_code, self.first_name, self.last_name)
    colored_name.allow_tags = True

class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'colored_name')

, , .

+4

Source: https://habr.com/ru/post/1746251/


All Articles