django如何显示项目数

时间:2018-11-10 21:59:46

标签: django

我想知道如何使用set_count计算问题模型中的民意调查数量 并且我也想在模板中显示它,请使用代码向我展示

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()

我要显示问题总数

1 个答案:

答案 0 :(得分:0)

这是您在 views.py 中写的:

首先,要进行计数,您必须导入模型本身


如果 models.py views.py 都属于同一个应用程序:

from .models import Question

如果它们属于不同的应用程序:

from <appname>.models import Question


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)

在函数的第一行,它仅使用django随附的.count()方法对问题进行计数。在第二行中,我们定义了要在模板中使用的上下文,在本例中为'number_of_questions':number_of_questions,因此在html模板中显示此数字时,我们将使用{{ number_of_question }},是否已定义如下: 'questions':number_of_questions,然后在模板中使用{{ questions }},最终结果将是显示number_of_questions

index.html 中(或任何您命名的模板):

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

如果您在理解任何内容时遇到困难,建议您通读以下内容:
Django documentation on templating

Some information about python dictionaries

编辑

我也强烈建议您阅读以下内容:

Django documentation about making queries to the database