Skip to content

Django db connection inconsistent between tests and view #2075

@Subaku

Description

@Subaku

Hello,

I just found a workaround to my problem but wanted to see if anyone has had this issue and might have suggestions. I'm using Django purely for its ORM feature with my Postgres DB but FastAPI for everything else. Note I'm not doing anything async.

Take a simple pytest using django-pytest:

import pytest

from my_django_models import Asset

@pytest.mark.django_db
class TestAssets:
...

    def test_response(self):
        assets = AssetFactory.create_batch(2)
        print(Asset.objects.all())
        resp = self.client.get('/assets')

The view:

from fastapi import APIRouter

from my_django_models import Asset

router = APIRouter()

@router.get('/assets')
def assets():
    print(Asset.objects.all())
    ...

The output:

[<Asset: Asset object (1)>, <Asset: Asset object (2)>]
<QuerySet []>

So the view has access to the db but it's not actually getting my data for some reason as if it has a bad or incorrect connection.
Now if I inherit from Django's TransactionTestCase class and continue using Starlette's TestClient it works... But I don't understand why. So for now that's what I'm doing but wanted to maybe get some clue into why this is the case.

As another note I have made sure I'm pointing at the right settings module and made sure django.setup() was called though I think django-pytest does this for me.

Appreciate any info.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions