与django-eztables聚合 [英] Aggregation with django-eztables
问题描述
我正在使用 django-eztables 做服务器端处理数据表。它到目前为止工作正常,但现在我试图添加一个字段到我的表,其中包含通过特定的外键与对象相关联的对象总数。使用fnRender可以在客户端上正确显示,但由于服务器端进行排序,所以我需要在服务器端进行聚合。这已经证明很困难。
I'm using django-eztables to do server-side processing of a datatable. It's been working fine so far, but now I'm trying to add a field to my table that contains the total number of objects associated with the object via a particular foreign key. It's easy enough to get this to display properly on the client side using fnRender, but since sorting is done on the server side, I need to actually do the aggregation on the server side. This has been proving difficult.
我似乎找不到在服务器端处理这种情况的方法。字段对象中的条目只是似乎接受实际的模型字段,我没有看到在我的谷歌发现建议的注释中的方法。我已经研究了定义自定义排序,但是因为我只是建立一个字符串,这似乎并没有什么帮助。
I can't seem to find a way to handle this on the server side. The entries in the fields object only seem to accept actual model fields, and I don't see a way to slip in the annotation suggested by my google findings. I've looked into defining a custom sort, but since I'm just building a string, this doesn't really seem to help.
理想情况下,我想找一种使用外部聚合的方式关键关系在字段字典中,如:
Ideally, I'd like to find a way to use an aggregation of the foreign key relationship right in the fields dictionary, something like:
fields = {
'id': 'id',
'name': 'name',
'total_items': 'items__count' #Something like this, where Item has a foreign key to the object the datatable is composed of
#More fields...
}
如果这不可能,或不可行,只是让它排序是基于聚合是好的,因为我可以从客户端更改表中显示的数据,我不需要做任何过滤。
If that's not possible, or not feasible, just making it so that the sorting is based on the aggregation is fine, since I can change the data displayed in the table from the client side, and I don't need to do any filtering.
推荐答案
我终于意识到我可以在我重写get_queryset的时候放入注释,像这样:
I eventually realized that I could put in the annotation in when I was overriding the get_queryset, like so:
def get_queryset(self):
qs = super(SomeObjectDataTableView, self).get_queryset()
return qs.select_related().annotate(items_count=Count('items'))
可能应该早点知道了...
Probably should have figured this out earlier...
这篇关于与django-eztables聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!