2013-12-20 40 views
0

我試圖運行下面的查詢:整理註釋和使用價值(),而在Django的ORM返回註釋

labels = AssetLabel.objects.filter(organization=request.organization).annotate(num_assets=Count('asset')) 
labels = list(labels.order_by('-num_assets')[:20].values('id', 'name')) 

這給了我一個錯誤:

FieldError: Cannot resolve keyword 'num_assets' into field. Choices are: asset, id, name, organization 

如果我添加num_assets.values(),那麼我不會收到錯誤。但是,我不希望num_assets被返回。有沒有辦法做到這一點?

回答

0

你應該values使用前annotate,從doc的例子:

You should also note that average_rating has been explicitly included in the list of values to be returned. This is required because of the ordering of the values() and annotate() clause.

ValuesQuerySet總是包含註釋字段,ITER它來刪除該字段,

values = labels.order_by('-num_assets')[:20].values('id', 'name') 
for value in values: 
    value.pop('num_assets') 
1

檢查功能extra,它有一個叫order_by的參數,所以你可以使用這個功能來定購給定的QuerySet

https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.extra

我想這可能是這樣的:

labels = AssetLabel.objects. \ 
    filter(organization=request.organization). \ 
    extra(
     select={'num_assets': "Count('asset')"}, 
     order_by=['num_assets'] 
    ) 
+0

它不工作,除非'ORDER_BY = [ 'NUM_ASSETS']'。 – iMom0

+0

更新,謝謝 – yedpodtrzitko