如何在Django的异步查询中获取模型示例的外键属性(以及多对多属性)?

dy1byipe  于 2022-11-26  发布在  Go
关注(0)|答案(1)|浏览(130)

在异步查询中,我希望获得外键和模型示例的多对多属性。在一个简单的例子中,我希望为模型Student的所有示例打印universitycourses
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.

如何修复此错误?

toe95027

toe950271#

这是我用来获取外键和多对多属性的方法(对于django 4.1或更高版本)。

async def main():
    async for student in Student.objects.all():

        print(student.name)

        university = await University.objects.aget(id=student.university_id)
        print(university.name)

        async for course in student.courses.all():
            print(course.name)

asyncio.run(main())

相关问题