How can I call model methods or properties from Django Admin?
Is there a natural way to display model methods or properties in the Django admin site? In my case I have base statistics for a character that are part of the model, but other things such as status effects which affect the total calculation for that 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 total calculated statistic alongside the field to change the base statistic in the Change Character admin page, but it is not clear to me how to incorporate that information into the page.
Nice 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')
That works for list pages, if you want custom data on edit page, you need to override template.
精彩评论