Django context must be a dict rather than QuerySet.

2021. 4. 3. 13:57파이썬/Django

render에 QuerySet을 전달해서 발생한 오류

def dashboard(request) :
    template = 'ocr/dashboard.html'
    chars = Trained_Box.objects.filter(status='registered').values('char').annotate(total=Count('char')).order_by('-total')
    return render(request, template, chars)

결과

<QuerySet [{'char': '다', 'total': 1483}, {'char': '이', 'total': 1342}, {'char': '니', 'total': 1240}, {'char': '가', 'total': 1073}, {'char': '로', 'total': 906}, {'char': '의', 'total': 883}, {'char': '하', 'total': 817}, {'char': '감', 'total': 774}, {'char': '자', 'total': 754}, {'char': '있', 'total': 749}, {'char': '세', 'total': 749}, {'char': '리', 'total': 749}, {'char': '을', 'total': 698}, {'char': '주', 'total': 644}, {'char': '부', 'total': 644}, {'char': '제', 'total': 642}, {'char': '수', 'total': 642}, {'char': '는', 'total': 642}, {'char': '도', 'total': 586}, {'char': '에', 'total': 564}, '...(remaining elements truncated)...']>

수정

def dashboard(request) :
    template = 'ocr/dashboard.html'
    chars = Trained_Box.objects.filter(status='registered').values('char').annotate(total=Count('char')).order_by('-total')
    print(chars)
    results = {
        'results' : chars
    }
    return render(request, template, results)

결과

{'results': <QuerySet [{'char': '다', 'total': 1483}, {'char': '이', 'total': 1342}, {'char': '니', 'total': 1240}, {'char': '가', 'total': 1073}, {'char': '로', 'total': 906}, {'char': '의', 'total': 883}, {'char': '하', 'total': 817}, {'char': '감', 'total': 774}, {'char': '자', 'total': 754}, {'char': '있', 'total': 749}, {'char': '세', 'total': 749}, {'char': '리', 'total': 749}, {'char': '을', 'total': 698}, {'char': '주', 'total': 644}, {'char': '부', 'total': 644}, {'char': '제', 'total': 642}, {'char': '수', 'total': 642}, {'char': '는', 'total': 642}, {'char': '도', 'total': 586}, {'char': '에', 'total': 564}, '...(remaining elements truncated)...']>}