문제

In my template, I want to get a count of all answers for a question where the Answer.Value = "YES"

I have two models:

class Question(models.Model):
    question = models.CharField(max_length=100)

class Answer(models.Model):
    question = models.ForeignKey(Question)
    value = models.CharField(max_length=3)

My View:

def questn(request, question_id):
    qobj = Question.objects.select_related().get(id="1")
    return render(request, 'base.html', {'qobj': qobj})

My Template (base.html):

{{ qobj.answer_set.count }} //returns total count of all answers
{{ qobj.answer_set.filter(value="Yes").count }} //breaks my page...

What is the proper way to get a count of all "Yes" answers for this question?

도움이 되었습니까?

해결책

Django is built so that you have to put logic in your view. The template is not supposed to contain "advanced logic".

Do the query in the view, send the results to the template.

    return render(request, 'base.html', {'qobj': qobj, 'yes_count': qobj.answer_set.filter(value="Yes").count()})

Template:

{{ yes_count }}

다른 팁

You could also write a custom template filter or use a model method for the desired effect, I believe that would be the "Djangoist" way to go.

Documentation on writing your own template tags and filters:

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

An example on a related question:

https://stackoverflow.com/a/1333277/1453607

Your question is pretty much a duplicate of this one:

django template system, calling a function inside a model

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top