views:

53

answers:

2

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!

+1  A: 

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', )
Manoj Govindan
This returns (none), even though there are 5 choices in each. :(
M.A.
I added the missing `return` statement to the `pcount` method. Did you miss that?
Manoj Govindan
yeah - i caught that. Still shows (None).
M.A.
@M.A.: quite strange. Can you see what `pcount` returns for any instance of `Poll` from the Django shell?
Manoj Govindan
+1  A: 

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()
Lincoln B
It still returns (None)... sigh...
M.A.
HA! i was having trouble because of capitalization. Strange.
M.A.
Both of these should work. If you don't use choice count anywhere else but the admin they you can define this on `ModelAdmin`, if you need the choice count available in several places you will want to use the model approach.
rebus