感谢这个帖子,我能够很容易地做计数和组通过查询在Django视图:

Django的等效为计数和组由

我在做我的应用程序是什么显示硬币类型和我的数据库对于一个国家面对可用值的列表,所以从英国硬币可能有“1文钱”或“6便士”的面值。该face_value是6,currency_type是“便士”中,存储在一个相关的表。

我有我的看法如下代码,让我90%的方式出现:

def coins_by_country(request, country_name):
    country = Country.objects.get(name=country_name)
    coin_values = Collectible.objects.filter(country=country.id, type=1).extra(select={'count': 'count(1)'},
                               order_by=['-count']).values('count', 'face_value', 'currency_type')
    coin_values.query.group_by = ['currency_type_id', 'face_value']
    return render_to_response('icollectit/coins_by_country.html', {'coin_values': coin_values, 'country': country } )

currency_type_id遇到作为存储在外键字段数(即4)。我想要做的就是获取真正的对象,它作为查询的一部分引用(货币的模式,所以我可以在我的模板Currency.name场)。

什么是做到这一点的最好方法是什么?

有帮助吗?

解决方案 2

select_related()让我相当接近,但要我补充一点,我选择到group_by条款各个领域。

所以,我试图在values()后追加select_related()。没有去。然后我尝试每一种不同的排列在查询中的不同位置。关闭,但并不完全。

我结束了“wimping去”,只是使用原始SQL,因为我已经知道如何编写SQL查询。

def coins_by_country(request, country_name):
    country = get_object_or_404(Country, name=country_name)
    cursor = connection.cursor()
    cursor.execute('SELECT count(*), face_value, collection_currency.name FROM collection_collectible, collection_currency WHERE collection_collectible.currency_type_id = collection_currency.id AND country_id=%s AND type=1 group by face_value, collection_currency.name', [country.id] )
    coin_values = cursor.fetchall()
    return render_to_response('icollectit/coins_by_country.html', {'coin_values': coin_values, 'country': country } )

如果有一种方法,以短语,在Django的查询集语言准确的查询我很好奇,想知道。我想,一个SQL与两列计数和分组连接不是超级罕见,所以我会感到惊讶,如果没有一个清晰的方式。

其他提示

您不能values()做到这一点。但有没有必要使用 - 你可以得到实际Collectible对象,每个人都会有一个currency_type属性,这将是相关的链接对象

和作为justinhamade表明,使用select_related()将有助于减少数据库的查询的数量。

将其组合在一起,你会得到:

coin_values = Collectible.objects.filter(country=country.id, 
                    type=1).extra(
                    select={'count': 'count(1)'}, 
                    order_by=['-count']
                ).select_related()

您是否尝试select_related() HTTP://文档。 djangoproject.com/en/dev/ref/models/querysets/#id4

我用了很多它似乎运作良好,那么你可以去coin_values.currency.name。

另外,我不认为你需要做的国家= country.id在你的过滤器,只是国=国,但我不知道有什么区别在于小于打字让其他。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top