Esempio n. 1
0
def annotate_with_comment_count(queryset):
    """
    Annotate queryset with comment count

    From: http://djangosnippets.org/snippets/1101/

    """
    commented_model = queryset.model
    contenttype = ContentType.objects.get_for_model(commented_model)
    commented_table = commented_model._meta.db_table
    comment_table = Comment._meta.db_table

    # NOTE: ::text is specific to PostgreSQL
    sql = 'SELECT COUNT(*) FROM %s WHERE %s=%%s AND %s=%s::text' % (
        _qn(comment_table),
        _qf(comment_table, 'content_type_id'),
        _qf(comment_table, 'object_pk'),
        _qf(commented_table, 'id')
    )

    return queryset.extra(select={'comment_count': sql},
                          select_params=(contenttype.pk,))
Esempio n. 2
0
def _qf(table, field):  # quote table and field
    return '{}.{}'.format(_qn(table), _qn(field))