I'm fairly new to Django and try to get a database for scientific reviews up and running. One of the things I would like to show is how many reviews have been published in each year.
In this example I used the following data:
year: number of reviews published
1999: 1
2019: 4
2022: 5
models.py
class Review(models.Model):
title = models.CharField(max_length=100,null=True)
doi = models.URLField(max_length=200,unique=True,null=True)
author = models.CharField("First author",max_length=100,null=True)
year = models.PositiveIntegerField(null=True)
views.py
from django.shortcuts import render
from .models import Review
from django.db.models import Count
def about(response):
reviews_year_count = Review.objects.values('year').annotate(Count('year'))
context = {'reviews_year_count':reviews_year_count}
return render(response, "main/about.html", context)
about.html
<html>
<body>
{{reviews_year_count|join:", "}}
</body>
</html>
output on localhost
Currently:
{'year': 1999, 'year__count': 1}, {'year': 2019, 'year__count': 4}, {'year': 2022, 'year__count': 5}
Aim:
1, 4, 5
What I can't figure out is how to get rid of the {'year': 1999, 'year__count': }
and only have the integer value there. I looked at Django documentation pages. One of the things I tried was add defer()
behind reviews_year_count = Review.objects.values('year').annotate(Count('year'))
but calling defer()
after values()
doesn’t make sense according to documentation.
My aim is to use the data as input for a chart using chartsjs.
CodePudding user response:
You can use python to get only list of values:
reviews_year_count = Review.objects.values('year').annotate(Count('year'))
reviews_year_count = [i['year__count'] for i in reviews_year_count]
It is possible to do with django ORM using values
too