Hacktoberfest 2026: los issues que los mantenedores marcaron para octubre, abiertos y aptos para principiantes. Explorar issues de Hacktoberfest

Deep nested objects in django won't work due to async

Abierto
#84 6 comentarios 3 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
35/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Estancado
Stack tecnológico
django, graphql, python
Área
api, backend, database

Línea de trabajo

Empieza con los ejemplos de resolvers de Subscription, TaskType y TaskResultType del issue y, después, reproduce la suscripción anidada task → result → profiles usando la configuración de Django. Rastrea dónde se produce el error de contexto asíncrono y verifica que la suscripción anidada completa devuelve los datos del perfil sin requerir workarounds adicionales en los resolvers.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

  • GraphQL AioWS version: (not using AioWS, only django-channels)
  • Python version: 3.8.2
  • Operating System: MacOSX
Description

I am trying to get clients to subscribe to my graphql with a nested object in django. The request looks like this:

subscription {
  taskUpdated(id:"04a5e92bc9084ad981481ab4314a1d33", updateInterval: 3) {
    id
    token
    result {
      id,
      profiles {
        id
      }
    }
  } 
}

Tasks contain one result which contain multiple profiles.

What I Did

In my subscription class I used the sync_to_async method which works if used for the first level:

class Subscription(graphene.ObjectType):
    task_updated = graphene.Field(
        TaskType, id=graphene.String(), update_interval=graphene.Int()
    )

    async def resolve_task_updated(root, info, id, update_interval):
        print("TRYING TO RESOLVE")
        while True:
            print("While true")
            task = await sync_to_async(Task.objects.get, thread_sensitive=True)(
                pk=id
            )
            yield task
            await asyncio.sleep(update_interval)

Using the query only targeting task.id everything works perfectly. Once I try to target task.result (which is a new object). I receive the error:

You cannot call this from an async context - use a thread or sync_to_async.

I managed to get a workaround by updating the TaskType and updating the resolver for the result like so:

class TaskType(DjangoObjectType):
    class Meta:
        model = TaskModel
        fields = "__all__"

    result = graphene.Field(TaskResultType)

    async def resolve_result(self, info):
        return await sync_to_async(
            TaskResult.objects.get, thread_sensitive=True
        )(task=self.id)

That way I could get to the next level (task -> result). When I try to subscribe to task -> result -> profiles there is no way to receive the data anymore. The same error from above is thrown. Even if I update the ResultType accordingly to fetch all profiles async:

class TaskResultType(DjangoObjectType):
    class Meta:
        model = TaskResult
        fields = "__all__"

    profiles = graphene.List(ProfileType)

    async def resolve_profiles(self, info):
        return await sync_to_async(
            Profile.objects.filter, thread_sensitive=True
        )(task_result=self.id)

I thought dynamic querying of objects and subscribing to nested objects would be an out of the box functionality but it is really difficult. I can't be the only person using this repo to actually receive ORM data?

Lenguaje dominante
Python
Estrellas
270
Forks
85
Métricas de merge de PR
Sin PR fusionados en 30 d

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de graphql-python/graphql-ws

Todos los issues de graphql-python/graphql-ws

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.