Django: no access to database from async function

  Kiến thức lập trình

I am writing tests for my Django application using asyncio and running into a database access issue.
Here is minimal code that reproduces the error:

import pytest
from authentication.models import User


@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
class TestDatabaseAccess:

    @pytest.fixture(autouse=True)
    def _fixture(self):
        User.objects.create(username='username')

    async def test_main(self):

        async def get_user_async(user_id):
            user = await sync_to_async(User.objects.get)(id=user_id)
            return user

        await get_user_async(1)

I get error:

 def execute(self, query, params=None):
    if params is None:
        return Database.Cursor.execute(self, query)
    query = self.convert_query(query)
   return Database.Cursor.execute(self, query, params)

E django.db.utils.OperationalError: no such table: authentication_customuser

What am I doing wrong?

My fixture works fine and has access to database, I can print all users form there
But async test throwing an error.

LEAVE A COMMENT