开发者

django modeladmin list_display

I'm trying to pla开发者_高级运维y with the Django's official tutorial. Specifically the modeladmin list_display:

http://docs.djangoproject.com/en/1.2/intro/tutorial02/#customize-the-admin-change-list

How can I add a column that displays the number of choices for each poll in the list?

Thanks!


You don't need to edit your model, to calculate columns for admin on the fly create a function in the ModelAdmin object that takes a second param, this will be the regular Poll model instance. Than write code just like you would in a model, you can ignore the self here since it doesn't have what you want.

class PollAdmin(admin.ModelAdmin)
    list_display = (<other_fields>, 'choice_count')

    def choice_count(self, model_instance):
        return model_instance.choice_set.count()


Add a custom method (say pcount) that returns the number of choices for a given Poll instance. You can then add this to the list_display attribute in your ModelAdmin subclass.

class Poll(models.Model):
    ...
    def pcount(self):
        return self.choice_set.count()


class PollAdmin(admin.ModelAdmin):
    list_display = (<other fields>, 'pcount', )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜