1👍
There are a few things I would do here to provide you the best solution.
First, you don’t need to include questionship
and answership
in your context. Your template can get them via stepfields.questions
and question.answers
.
Next, to limit your list to 3, I would implement a template filter. This could be done using slices, like this:
register = template.Library()
@register.filter
def limit_to_3(list, arg):
return list[0:arg]
You could then, in your template, change your {% for %}
loops to be this format:
{% for question in stepfieldst.questions|limit:3 %}
{% for answer in question.answers|limit:3 %}
{% endfor %}
{% endfor %}
Depending if your number of questions and answers per article are low enough that querying them all would be less burdensome than multiple queries, you could do something like this:
try:
stepfieldst = Step.objects.select_related(questions__answers).filter(id = question_id)
except Step.DoesNotExist:
raise Http404
This would select all related questions and answers in a single query.
Source:stackexchange.com