I'd like to add "annotation count" field into list_display in Django Admin.
models.py
class Log(models.Model):
...
ip_address = models.GenericIPAddressField(
verbose_name=_('IP address'),
db_index=True,
)
...
admin.py
class LogAdmin(admin.ModelAdmin):
list_display = (..., 'ip_address', 'ip_address_count', ...)
def ip_address_count(self, instance):
return models.Log.objects \
.filter(ip_address=instance.ip_address) \
.count()
ip_address_count.short_description = _('IP Address Count')
It works fine with "LOTS OF" SQL queries.
I'd like to improve my admin.py
like this:
class Log(models.Model):
...
def get_queryset(self, request):
qs = super(LogAdmin, self).get_queryset(request)
qs = qs.values('ip_address') \
.annotate(ip_address_count=Count('ip_address'))
return qs
def ip_address_count(self, instance):
return instance.ip_address_count
However, I encountered the error messages:
'dict' object has no attribute '_meta'
It seems that I found the reason why the error occurs:
Django Admin, can't groupe by: Exception Value: 'dict' object has no attribute '_meta'
However, it does not help me to solve the problem.
Thank you for your answers.
Edit: It works wrong if I don't append .values('ip_address)
.
It does not group by ip_address
. It group by
all the fields group by field1, field2, ip_address, ...
Therefore, it results in "1" all the cases.