# Buggy code
async def _prefetch_m2m_relation(
    self, instance_list: list, field: str, related_query
) -> list:
    instance_id_set: set = {
        self._field_to_db(instance._meta.pk, instance.pk, instance)
        for instance in instance_list
    }

    field_object: fields.ManyToManyFieldInstance = self.model._meta.fields_map[  # type: ignore
        field
    ]

    through_table = Table(field_object.through)

    subquery = (
        self.db.query_class.from_(through_table)
        .select(
            getattr(through_table, field_object.backward_key).as_(
                "_backward_relation_key"
            ),
            getattr(through_table, field_object.forward_key).as_(
                "_forward_relation_key"
            ),
        )
        .where(getattr(through_table, field_object.backward_key).isin(instance_id_set))
    )

    related_query_table = Table(related_query.model._meta.table)
    related_pk_field = related_query.model._meta.db_pk_field
    query = (
        related_query.query.join(subquery)
        .on(
            subquery._forward_relation_key
            == getattr(related_query_table, related_pk_field)
        )
        .select(
            subquery._backward_relation_key.as_("_backward_relation_key"),
            *[
                getattr(related_query_table, field).as_(field)
                for field in related_query.fields
            ],
        )
    )

    if related_query._q_objects:
        joined_tables: List[Table] = []
        modifier = QueryModifier()
        for node in related_query._q_objects:
            modifier &= node.resolve(
                model=related_query.model,
                annotations=related_query._annotations,
                custom_filters=related_query._custom_filters,
            )

        where_criterion, joins, having_criterion = modifier.get_query_modifiers()
        for join in joins:
            if join[0] not in joined_tables:
                query = query.join(join[0], how=JoinType.left_outer).on(join[1])
                joined_tables.append(join[0])

        if where_criterion:
            query = query.where(where_criterion)

        if having_criterion:
            query = query.having(having_criterion)

    raw_results = await self.db.execute_query(query.get_sql())
    relations = {
        (
            self.model._meta.pk.to_python_value(e["_backward_relation_key"]),
            field_object.field_type._meta.pk.to_python_value(e[related_pk_field]),
        )
        for e in raw_results
    }
    related_object_list = [related_query.model._init_from_db(**e) for e in raw_results]
    await self.__class__(
        model=related_query.model, db=self.db, prefetch_map=related_query._prefetch_map
    ).fetch_for_list(related_object_list)
    related_object_map = {e.pk: e for e in related_object_list}
    relation_map: Dict[str, list] = {}

    for object_id, related_object_id in relations:
        if object_id not in relation_map:
            relation_map[object_id] = []
        relation_map[object_id].append(related_object_map[related_object_id])

    for instance in instance_list:
        relation_container = getattr(instance, field)
        relation_container._set_result_for_query(relation_map.get(instance.pk, []))
    return instance_list


# Traceback (AttributeError)
Traceback (most recent call last):
File "/opt/project/src/server.py", line 54, in <module>
asyncio.run(main())
File "/usr/local/lib/python3.7/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/usr/local/lib/python3.7/asyncio/base_events.py", line 579, in run_until_complete
return future.result()
File "/opt/project/src/server.py", line 47, in main
async for item in ModelOne.all().prefetch_related('many_to_many'):
File "/usr/local/lib/python3.7/site-packages/tortoise/queryset.py", line 512, in __aiter__
for val in await self:
File "/usr/local/lib/python3.7/site-packages/tortoise/queryset.py", line 521, in _execute
).execute_select(self.query, custom_fields=list(self._annotations.keys()))
File "/usr/local/lib/python3.7/site-packages/tortoise/backends/base/executor.py", line 90, in execute_select
await self._execute_prefetch_queries(instance_list)
File "/usr/local/lib/python3.7/site-packages/tortoise/backends/base/executor.py", line 327, in _execute_prefetch_queries
await self._do_prefetch(instance_list, field, related_query)
File "/usr/local/lib/python3.7/site-packages/tortoise/backends/base/executor.py", line 320, in _do_prefetch
return await self._prefetch_m2m_relation(instance_id_list, field, related_query)
File "/usr/local/lib/python3.7/site-packages/tortoise/backends/base/executor.py", line 232, in _prefetch_m2m_relation
*[getattr(related_query_table, field).as_(field) for field in related_query.fields],
File "/usr/local/lib/python3.7/site-packages/tortoise/backends/base/executor.py", line 232, in <listcomp>
*[getattr(related_query_table, field).as_(field) for field in related_query.fields],
AttributeError: 'NoneType' object has no attribute 'as_'

# Fixed code
async def _prefetch_m2m_relation(
    self, instance_list: list, field: str, related_query
) -> list:
    instance_id_set: set = {
        self._field_to_db(instance._meta.pk, instance.pk, instance)
        for instance in instance_list
    }

    field_object: fields.ManyToManyFieldInstance = self.model._meta.fields_map[  # type: ignore
        field
    ]

    through_table = Table(field_object.through)

    subquery = (
        self.db.query_class.from_(through_table)
        .select(
            through_table[field_object.backward_key].as_("_backward_relation_key"),
            through_table[field_object.forward_key].as_("_forward_relation_key"),
        )
        .where(through_table[field_object.backward_key].isin(instance_id_set))
    )

    related_query_table = Table(related_query.model._meta.table)
    related_pk_field = related_query.model._meta.db_pk_field
    query = (
        related_query.query.join(subquery)
        .on(subquery._forward_relation_key == related_query_table[related_pk_field])
        .select(
            subquery._backward_relation_key.as_("_backward_relation_key"),
            *[related_query_table[field].as_(field) for field in related_query.fields],
        )
    )

    if related_query._q_objects:
        joined_tables: List[Table] = []
        modifier = QueryModifier()
        for node in related_query._q_objects:
            modifier &= node.resolve(
                model=related_query.model,
                annotations=related_query._annotations,
                custom_filters=related_query._custom_filters,
            )

        where_criterion, joins, having_criterion = modifier.get_query_modifiers()
        for join in joins:
            if join[0] not in joined_tables:
                query = query.join(join[0], how=JoinType.left_outer).on(join[1])
                joined_tables.append(join[0])

        if where_criterion:
            query = query.where(where_criterion)

        if having_criterion:
            query = query.having(having_criterion)

    raw_results = await self.db.execute_query(query.get_sql())
    relations = {
        (
            self.model._meta.pk.to_python_value(e["_backward_relation_key"]),
            field_object.field_type._meta.pk.to_python_value(e[related_pk_field]),
        )
        for e in raw_results
    }
    related_object_list = [related_query.model._init_from_db(**e) for e in raw_results]
    await self.__class__(
        model=related_query.model, db=self.db, prefetch_map=related_query._prefetch_map
    ).fetch_for_list(related_object_list)
    related_object_map = {e.pk: e for e in related_object_list}
    relation_map: Dict[str, list] = {}

    for object_id, related_object_id in relations:
        if object_id not in relation_map:
            relation_map[object_id] = []
        relation_map[object_id].append(related_object_map[related_object_id])

    for instance in instance_list:
        relation_container = getattr(instance, field)
        relation_container._set_result_for_query(relation_map.get(instance.pk, []))
    return instance_list