を重複しました。DjangoのSQLクエリは、私はこれを含む<strong>models.py</strong>ファイルを持っている
私がしようとしているのは、質問された最後の5つの質問を取得し、それらの質問への回答、回答を提供したユーザー、そのユーザーのアバターなどを含むいくつかのデータとともに私のホームページに表示します。
views.py:と等...
私は現在、このviews.pyとhome.htmlテンプレートであることをやっている
home.html@login_required(login_url="accounts/login/")
def home_page(request):
last_five = Question.objects.all().order_by('-id')[:5]
last_five_in_ascending_order = list(reversed(last_five))
return render(request, 'home.html', {
'question_list': last_five_in_ascending_order,
})
:
{% for question in question_list %}
<a href="{% url 'view_question' question.id %}">{{ question.text }}</a>
{% if question.answer_set.all %}
{% for answer in question.answer_set.all %}
<img src="/media/{{ answer.created_by.userprofile.avatar }}" alt="">
<a href="{% url 'profile' answer.created_by.id %}">
{% firstof answer.created_by.get_full_name answer.created_by.username %}
</a>
{{ answer.time_passed }}
{{ answer.text | safe }}
{% endfor %}
{% endif %}
{% endfor %}
データベースへのSQLクエリを減らすにはどうすればよいですか? 本当にこれらのことが心配すべきですか?ユーザーの活動がほとんどないウェブサイトに違いがありますか?
あなたの質問は何ですか? – zaidfazil
おそらく関連している:https://stackoverflow.com/q/33587557/3901060。 select_related(またはprefetch_related)QuerySetメソッドを使用して、質問とその回答を1つのクエリで結合します。 – FamousJameous
@FazilZaid私は質問を忘れた:))私は今それを追加しました。 – arianhf