问题
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
回答1:
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
来源:https://stackoverflow.com/questions/28655840/django-admin-cant-groupe-by-exception-value-dict-object-has-no-attribute