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

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

在异步查询中,我想获取模型实例的外键和多对多属性。 在一个简单的示例中,我想为模型的所有实例打印

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.

如何修复此错误?

python django asynchronous async-await
1个回答
0
投票

这是我在异步查询中获取外键和多对多属性(对于 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)
© www.soinside.com 2019 - 2024. All rights reserved.