简体   繁体   中英

Django admin list view

I have Model like:

class MyModel(models.Model):
  user = models.ForeignKey(User)
  field1 = models.CharField(max_length=100, db_index=True, null=False, blank=False)
  field2 = models.CharField(max_length=100)

Of course it is shown as list like:

user1 | field1 | field2
user1 | field1 | field2
user2 | field1 | field2
user2 | field1 | field2

I would like to show it like:

user1 | field1_count() | field2_count()
user2 | field1_count() | field2_count()

I know how to calculate field1_count() and field2_count() for user, but how keep only one row per user?

You could use the list_display attribute to define which fields are displayed in the change list page of the admin.

class MyAdmin(admin.ModelAdmin):
    list_display = ('username', 'field1_count', 'field2_count')

    def field1_count(self, obj):
        # count field1
        return c

    def field2_count(self, obj):
        # count field2
        return c

 admin.site.register(User, MyAdmin)

Note that this will make at least two queries per row in your change list page, which might or might not be a problem in your case.

Alternatively, you can try overwriting either ModelAdmin.queryset or ModelAdmin.changelist_view .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM