You have an admin for the
Origin
model like this:@admin.register(Origin)
class OriginAdmin(admin.ModelAdmin):
list_display = ("name",)
Apart from the name, we also want to show the number of heroes and number of villains for each origin, which is not a DB field on
Origin
. You can do this in two ways.7.1. Adding a method to the model
You can add two methods to your
Origin
model like this:def hero_count(self,):
return self.hero_set.count()
def villain_count(self):
return self.villain_set.count()
And change
list_display
to list_display = ("name", "hero_count", "villain_count")
.7.2. Adding a method to the ModelAdmin
If you don’t want to add method to the model, you can do instead add the method to the ModelAdmin.
def hero_count(self, obj):
return obj.hero_set.count()
def villain_count(self, obj):
return obj.villain_set.count()
The
list_display
, as earlier, changes to list_display = ("name", "hero_count", "villain_count")
.7.3. Performance considerations for calculated_fields
With either of the above approaches, you would be running two exta queries per object (One per calculated field). You can find how to optimize this in How to optimize queries in Django admin?.
With any of these changes your admin looks like this:
No comments:
Post a Comment