Accessing the values of a relationship field in a Django Dashboard
When you would like to group your instances of model by a category that stands in relationship to this model like the following:
from django.db import models
class model1(models.Model):
name = models.CharField(max_length=256)
def __str__(self):
return self.name
class model2(models.Model):
some_other_name = models.CharField(max_length=256)
name_model_1 = models.ForeignKey(model1, on_delete=models.CASCADE)
def __str__(self):
return self.some_other_name
You might run into the problem that when you group the objects of your model2
by the field name_model_1
that you actually don’t get the exact values of this field. Instead you will be given the id of the belonging field, in this case name. But when you would like to visualise your data in a bar chart like the django extension django-controlcenter. In this case you can easily modify your queryset by just extending the string selection with the double underscore:
from controlcenter import Dashboard, widgets
from app.models import your_model
class SingleBarChartExample(widgets.SingleBarChart):
# label and series
title = 'Your label'
values_list = ('name_model_1__name', 'dcount')
# Grouping the data
queryset = your_model.objects.values('name_model_1__name').annotate(dcount=Count('name_model_1__name'))