在异步查询中,我想获取模型实例的外键和多对多属性。 在一个简单的示例中,我想为模型的所有实例打印
university
和 courses
Student
。
models.py:
from django.db import models
class University(models.Model):
name = models.CharField(max_length=64)
class Course(models.Model):
name = models.CharField(max_length=64)
class Student(models.Model):
name = models.CharField(max_length=64)
university = models.ForeignKey(to=University, on_delete=models.CASCADE)
courses = models.ManyToManyField(to=Course)
当我使用此代码时(在 django 4.1 中):
import asyncio
async def main():
async for student in Student.objects.all():
print(student.name)
print(student.university.name)
for course in student.courses.all():
print(course.name)
asyncio.run(main())
我收到以下错误:
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
如何修复此错误?
这是我在异步查询中获取外键和多对多属性(对于 django 4.1 或更高版本)的方法:
获取外键属性有两种选择:
1-
async for student in Student.objects.all():
university = await University.objects.aget(id=student.university_id)
print(university.name)
2-
async for student in Student.objects.select_related("university").all():
print(student.university.name)
async for student in Student.objects.all():
async for course in student.courses.all():
print(course.name)