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 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 file…

Here is my file code…

def diaplay_view(request):
    possessions = ProjectDetails.objects.values('possession').annotate(
    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 %}


Please enter your comment!
Please enter your name here