Suppose you have 2 models, one is Project and another is ProjectDetails, and you want to count any one field value from ProjectDetails model, Then you can use this Query.

First Create class in models.py file…

class Project(models.Model):
    name=models.CharField(max_length= 225)
    slug=models.SlugField(null=True, unique=True)

class ProjectDetails(models.Model):
    project = models.OneToOneField('Project', related_name='detailsofpro', on_delete=models.CASCADE, blank=True, null=True)
    possession = models.CharField(max_length=50, null=True, blank=True, choices=(('Under Construction', 'Under Construction'),('New launch', 'New Launch'),('Ready To Move', 'Ready To Move')))

I want to count possession field value from ProjectDetails model, then i will write some this code in my views.py file…

Here is my views.py file code…

def diaplay_view(request):
    possessions = ProjectDetails.objects.values('possession').annotate(
        nprojects=Count('project')
    ).order_by('possession')
    return render(request, 'index.html', {'possessions': possessions})

my index.html file will be something like this…

{% for item in possessions %}
    {{ item.possession }}: {{ item.nprojects }}<br>
{% endfor %}

LEAVE A REPLY

Please enter your comment!
Please enter your name here