Extract data for statistics

I have two models:

class Log(models.Model): ... country = models.ForeignKey(Country, null=True, blank=True) ... user = models.ForeignKey('auth.User') class Country(models.Model): name = models.CharField(max_length=50) alpha_2_code = models.CharField("Alpha-2 code", max_length=2, unique=True) alpha_3_code = models.CharField("Alpha-3 code", max_length=3, unique=True) numeric_code = models.PositiveSmallIntegerField("Numeric code", max_length=3, unique=True) order = models.SmallIntegerField(max_length=3) continent = models.ForeignKey(Continent) def __unicode__(self): return self.name 

What I'm trying to do is display a Google Map based on log entries, so what I have to pass to the templates looks something like this:

  function drawRegionsMap() { var data = google.visualization.arrayToDataTable([ ['Country', 'Popularity'], ['Germany', 200], ['United States', 300], ['Brazil', 400], ['Canada', 500], ['France', 600], ['RU', 700] ]); 

What is the fastest way to extract and pass data to templates?

+4
source share
1 answer

I assume popularity is defined as the SQL count the Log model, grouped by country. Correct me if I am wrong. See the aggregation documentation for more information.

 from django.db.models import Count queryset = Log.objects.values('country__name').annotate(popularity=Count('country__name')) 

Then in your template you will do the following:

 var data = google.visualization.arrayToDataTable([ ['Country', 'Popularity'], {% for log in queryset %} ['{{ log.country.name }}', {{ log.popularity }} ] {% if not forloop.last %},{% endif %} {% endfor %} ]); 

Note that in the template, I check forloop for the last iteration and not including the trailing comma if this is the last iteration.

+3
source

Source: https://habr.com/ru/post/1491518/


All Articles