Question

I would like to display how many relations an object has in the Django admin.

Let's say I have the following models:

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

And I would like to display in the admin (list_display) next to the Poll Question the amount of choices there are. Is there a way to add a function to the class Question that will return how many choices it has?

Edit

This is a hypothetical model. I am using models with file storage and would like to count how many files are connected to the "main" model, or in this case, the Question class.

Was it helpful?

Solution

The list_display option allows you to specify functions on the ModelAdmin itself to display as columns. You don't even need to define that function on your Question model, if you're only going to need it for your ModelAdmin.

From the docs of list_display:

class PersonAdmin(admin.ModelAdmin):
    list_display = ('upper_case_name',)

    def upper_case_name(self, obj):
        return ("%s %s" % (obj.first_name, obj.last_name)).upper()
    upper_case_name.short_description = 'Name'

A function specified in your list_display attribute will be called with a single parameter: the object that is being displayed. You can obtain the count of its related instances using RelatedManager.count on your reverse relation:

return obj.choice_set.count()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top