4

I have this model which maps to a postgresql view

class AppModel(models.Model):

    nbr = models.BigIntegerField(blank=True, null=True)
    region = models.ForeignKey(AppWilaya,blank=True, null=True)
    date_preorder = models.DateField(blank=True, null=True)
    id = models.IntegerField(primary_key=True,blank=True, db_column='dummy_id')

What I want to achieve is to sum "nbr" by "region", so:

class AppModelAdmin(admin.ModelAdmin):
....
def queryset(self, request):
        qs = super(AppModelAdmin, self).get_queryset(request)  
        qs=qs.values("region").annotate(total=Sum( 'nbr'))

But Django Admin seems not accepting .values("region") as an exception is thrown:

Exception Value: 'dict' object has no attribute '_meta'
Exception Location: [PATH_TO]\lib\site-packages\django\contrib\admin\util.py in lookup_field, line 242
elsadek
  • 1,028
  • 12
  • 39
  • I suspected a bug behind this exception, which was not accepted https://code.djangoproject.com/ticket/24387 – elsadek Mar 12 '15 at 06:23

1 Answers1

2

First of all, it looks like you are using Django 1.6, which changed the use of queryset to get_queryset. So to prevent any confusion, just use get_queryset or use a different name altogether if this is not what you intend.

The get_queryset method in ModelAdmin has the following description in the documentation (emphasis mine):

The get_queryset method on a ModelAdmin returns a QuerySet of all model instances that can be edited by the admin site.

Your implementation of queryset returns a projection, which is not a model (something containing _meta), but a dictionary, hence the exception.

It is therefore not a problem with your query in itself, but a problem of where you use it. The get_queryset method is not the right place to do what you want.

If you want to use this information for filtering, have a look at creating a custom filter. If you want to show this information as one of the fields in your changelist, use a callable in list_display

publysher
  • 11,214
  • 1
  • 23
  • 28
  • if _get_queryset method is not the right place_ , then how is it possible to to display grouped data that leverage filters features in the admin list ? – elsadek Mar 13 '15 at 15:49
  • you can't use _callable_ to achieve _aggregation_ on a set of model instances. – elsadek Mar 13 '15 at 19:31
  • Not for arbitrary sets, no. If you want your aggregation to be done over (e.g.) the current change-list selection, I'm afraid you'll have to look at extending the admin templates and calling custom methods from there. Remember: the admin is not your app! http://stackoverflow.com/a/677509/1636314 – publysher Mar 14 '15 at 08:15