在异步查询中,我希望获得外键和模型示例的多对多属性。在一个简单的例子中,我希望为模型Student
的所有示例打印university
和courses
。
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.
如何修复此错误?
1条答案
按热度按时间toe950271#
这是我用来获取外键和多对多属性的方法(对于django 4.1或更高版本)。