如何使 Django 模板变量异步工作?

问题描述 投票:0回答:1

我正在尝试将异步方法应用于现有的 Django 项目,更新视图会出现此错误:

django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

views.py

@sync_to_async
def get_educations():
  return Education.objects.filter(highlight=True).order_by("-order")

async def home(request):
  return render(request, "home.html", {
    "educations": await get_educations(),
  })

home.html

<section class="d-flex flex-column">
<h3 class="section">Education</h3>
{% for education in educations %}
  {% include "preview_education.html" %}
{% endfor %}

尝试使用

return [Education.objects.first()]
效果很好。

知道如何解决吗?

django
1个回答
0
投票

解决方案是将 Django Queryset 转换为列表并使用

select_related
与模型关系。

views.py:

@sync_to_async
def get_educations():
  return list(
    Education.objects.filter(
      highlight=True
    )
    .select_related('organization')
    .order_by("-order")
  )

async def home(request):
  return render(request, "home.html", {
    "educations": await get_educations()
  }

home.html:

<section class="d-flex flex-column">
  <h3 class="section">Education</h3>
  {% for education in educations %}
    <article class="element">
      <h4>{{ education.name }}</h4>
      <p>{{ education.organization }}</p>
      <p>{{ education.place }}</p>
      <p>{{ education.duration }}</p>
    </article>
  {% endfor %}
</section>
© www.soinside.com 2019 - 2024. All rights reserved.