Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not allowed to call async on function converted with sync_to_async()

I am having problems with sync_to_async. I am getting the You cannot call this from an async context - use a thread or sync_to_async. error at the print statement, even though I used sync_to_async to convert the async function. If I do print(type(masters)) instead, i get a QuerySet as type. Is there something I am missing? I couldn’t find this specific case on the docs.

Here is my code:

import discord
from discord.ext import commands
from asgiref.sync import sync_to_async


class Bot(commands.Bot):
    # ...
    async def on_message(self, msg):
        masters = await sync_to_async(self.subject.masters)()
        print(masters)

Here is the masters() function i’m trying to get results from:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from django.db import models


class Subject(models.Model):
    # ...
    def masters(self):
        from .subjectmaster import SubjectMaster
        return SubjectMaster.objects.filter(subject=self)

>Solution :

Your QuerySet is not executed until it is printed and you print outside of the sync_to_async function. You need to evaluate the QuerySet in your method

class Subject(models.Model):

    def masters(self):
        from .subjectmaster import SubjectMaster
        # Force evaluation by converting to a list
        return list(SubjectMaster.objects.filter(subject=self))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading