Django Admin,不能按以下项分组:异常值:'dict'对象没有属性'_meta' [英] Django Admin, can't groupe by: Exception Value: 'dict' object has no attribute '_meta'
问题描述
我有一个映射到PostgreSQL视图的模型
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')
我要实现的是按区域 总结 nbr ,所以:
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'))
但是Django Admin似乎不接受 .values( region),因为抛出了异常:
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
推荐答案
首先,您似乎正在使用Django 1.6,它更改了 queryset $ c的用法$ c>到
get_queryset
。因此,为避免任何混乱,请使用 get_queryset
或在您不打算使用的情况下完全使用其他名称。
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.
ModelAdmin中的 get_queryset
方法在文档(强调我的意思):
The get_queryset
method in ModelAdmin has the following description in the documentation (emphasis mine):
ModelAdmin上的get_queryset方法返回所有模型实例的查询集,可以由管理站点进行编辑。
The get_queryset method on a ModelAdmin returns a QuerySet of all model instances that can be edited by the admin site.
您对 queryset
的实现返回一个投影,这不是 模型(包含 _meta
),但有字典,因此是例外。
Your implementation of queryset
returns a projection, which is not a model (something containing _meta
), but a dictionary, hence the exception.
因此,查询本身并不是问题,而是使用位置的问题。 get_queryset
方法不是执行所需操作的正确位置。
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.
如果要使用此信息进行过滤,请查看创建自定义过滤器。如果要将此信息显示为变更列表中的字段之一,请在 list_display
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
这篇关于Django Admin,不能按以下项分组:异常值:'dict'对象没有属性'_meta'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!