Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotation in Django Admin

I have a model as below:

.......
user=models.ForeignKey(settings.AUTH_USER_MODEL,null=True,blank=True)
visited = models.CharField(max_length=15)
......

I want to see in Django admin, each user with visited count. As of now I get name of each user multiple times and count is 1.

This is my admin.py.

class modelnameadmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super(modelnameadmin, self).get_queryset(request)
        return qs.annotate(visit_count=Count('visited',distinct=True)).order_by('visit_count')

    def visit_count(self, inst):
        return inst.visit_count

    list_display = ['user','visit_count']

I am getting below results in admin template.

user      visit_count
1          1
1          1
2          1
2          1

But I should get result as below.

user      visit_count
1          2
2          2
like image 833
Sapna Sharma Avatar asked Jun 11 '19 12:06

Sapna Sharma


1 Answers

Suppose your model is something like below.

models.py

from django.db import models
from django.contrib.auth.models import User

class MyModel(models.Model):
    user = models.ForeignKey(User, null=True, blank=True)
    visit_count = models.PositiveIntigerField(default=0)

So you can using values attribute on your queryset in order to GROUP BY the queryset based on user first, then try to aggregate visit_count for each user.

admin.py

from django.db.models.aggregates import Sum
from django.contrib import admin

from .models import MyModel

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    list_display = ['user', 'visit_sum']

    def get_queryset(self, request):
        queryset = super(MyModelAdmin, self).get_queryset(request)
        return queryset.values('user').annotate(visit_sum=Sum('visit_count')).order_by('-visit_sum')

    def visit_sum(self, obj):
        return obj.visit_sum
like image 82
mrzrm Avatar answered Oct 11 '22 18:10

mrzrm