Django - 当我使用values_list时,无法将关键字'count_number'解析为字段

时间:2022-04-20 01:35:24

There is a query:

有一个查询:

selected = MyModel.objects.filter(category_id=category_id,status__gte=0) \
               .filter(pub_time__lte=_refresh_datetime,
                       buy_links__status=2) \
               .annotate(like_count=Count('likes'))\
               .order_by('-like_count')

it works, but, When I need to get id of this query:

它工作,但是,当我需要获取此查询的ID:

selected_id_list = selected.values_list('id')

Raised:

Cannot resolve keyword 'like_count' into field. Choices are: ....

无法将关键字'like_count'解析为字段。选择是:....

Anyone knows about this?

谁知道这件事?

ps,

Python version: 2.7.10

Python版本:2.7.10

Django version: 1.6.11

Django版本:1.6.11

1 个解决方案

#1


0  

Try values_list('id', 'like_count'). I don't know Django much, but the annotated filed must appear in the SELECT expression. It looks like with values_list('id'), the generated query becomes SELECT id FROM ..., in which case count(likes) is missing from the SELECT expression.

尝试values_list('id','like_count')。我不太了解Django,但注释的字段必须出现在SELECT表达式中。看起来像values_list('id'),生成的查询变为SELECT id FROM ...,在这种情况下,SELECT表达式中缺少count(likes)。

In sum, selected_id_list = [r[0] for r in selected.values_list('id', 'like_count')]

总而言之,selected_id_list = [r [0]表示选定的.values_list中的r('id','like_count')]

#1


0  

Try values_list('id', 'like_count'). I don't know Django much, but the annotated filed must appear in the SELECT expression. It looks like with values_list('id'), the generated query becomes SELECT id FROM ..., in which case count(likes) is missing from the SELECT expression.

尝试values_list('id','like_count')。我不太了解Django,但注释的字段必须出现在SELECT表达式中。看起来像values_list('id'),生成的查询变为SELECT id FROM ...,在这种情况下,SELECT表达式中缺少count(likes)。

In sum, selected_id_list = [r[0] for r in selected.values_list('id', 'like_count')]

总而言之,selected_id_list = [r [0]表示选定的.values_list中的r('id','like_count')]