Shadrack Shadrack
Shadrack Shadrack

Reputation: 21

django how to display number of items

I was wondering how I do count the number of poll in my question model using set_count and I also want to display it in a template please show me using the code thanks

class Question(models.Model):

    question_text = models.CharField(max_length=10)

    pub_date = models.DateTimeField('date published')


    def __str__(self):

        return self.question_text

    def was_published_recently(self):

        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)


class Choice(models.Model):

    question = models.ForeignKey(Question, on_delete=models.CASCADE)

    title = models.CharField(max_length=10)

    site_url = models.URLField()

    website_type = models.CharField(max_length=100)

    budget = models.CharField(max_length=100)

    duration = models.CharField(max_length=100)

    description = models.TextField()

I want the show the total of question

Upvotes: 1

Views: 622

Answers (1)

user10317280
user10317280

Reputation:

This is what you write in your views.py:

First, to count it, you have to import the model itself


If models.py and views.py both belong to same app:

from .models import Question

If they belong to different apps:

from <appname>.models import Question


I'll assume they belong to the same app, in views.py:

from django.shortcuts import render

from .models import Question

def index(request):
    number_of_questions = Question.objects.count()
    context = {
        'number_of_questions':number_of_questions,
    }
    return render(request, '<appname>/index.hmtl>', context)

On the first line of the function it just counts the number of questions with .count() method which comes with django. On the second line we define context that we want to use in template, in this case 'number_of_questions':number_of_questions, so in the html template to display this number we'll use {{ number_of_question }}, have we defined it like so: 'questions':number_of_questions, then in the template we would use {{ questions }}, the end result will be that it shows number_of_questions.

In index.html (Or whatever you named the template):

<p>number of questions:</p>
    <p>{{ number_of_questions }}

If you have trouble understanding anything I suggest you read through these:
Django documentation on templating

Some information about python dictionaries

EDIT:

I also highly recommend reading this:

Django documentation about making queries to the database

Upvotes: 1

Related Questions