M.A.
M.A.

Reputation: 31

django modeladmin list_display

I'm trying to play 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!

Upvotes: 3

Views: 1755

Answers (2)

Lincoln B
Lincoln B

Reputation: 2214

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()

Upvotes: 3

Manoj Govindan
Manoj Govindan

Reputation: 74675

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', )

Upvotes: 1

Related Questions