Skip to content

Conversation

ddrondo
Copy link

@ddrondo ddrondo commented Sep 27, 2025

I ran into a problem during a transaction when I call the POST create method in the view and try to create documents through the serializer:

class CreateTariff(TariffsSerializer):
    @transaction.atomic(using="mongodb")
    def create(self, validated_data):
        ...

This error occurs spontaneously and always at the first call to the endpoints API.

File: C\test\venv\lib\site-packages\rest_framework\views.py in dispatch (line 506)
response = handler(request, *args, **kwargs)

File: C:\test\venv\lib\site-packages\rest_framework\mixins.py in create (line 19)
self.perform_create(serializer)

File: C:\test\venv\lib\site-packages\rest_framework\mixins.py in perform_create (line 24)
serializer.save()

File: C:\test\venv\lib\site-packages\rest_framework\serializers.py in save (line 208)
self.instance = self.create(validated_data)

...

File: C:\test\venv\lib\site-packages\django_mongodb_backend\transaction.py in __enter__ (line 29)
connection.start_transaction_mongo()

File: C:\test\venv\lib\site-packages\django\utils\asyncio.py in inner (line 26)
return func(*args, **kwargs)

File: C:\test\venv\lib\site-packages\django_mongodb_backend\base.py in start_transaction_mongo (line 275)
self.session = self.connection.start_session()
Error: 'NoneType' object has no attribute 'start_session'

As I understand it, it occurs due to the fact that the connection lazily creates a connection (connection.connection) during the entry into the transaction.

@timgraham timgraham changed the title DB Connection is None in transaction INTPYTHON-772 Fix transaction.atomic() crash if connection isn't initialized Sep 27, 2025
@timgraham
Copy link
Collaborator

timgraham commented Sep 27, 2025

Thank you. transaction.atomic() is modeled off of django.transaction.atomic() so I don't think we want the logic added there. I'll amend this and add a test.

I don't like having to add ensure_connection() in various places (this also came up in the showencryptedfields management command of #329), but the alternative of a __getattr__() hack [5febcd3 removed it] isn't nice either.

Copy link
Collaborator

@aclark4life aclark4life left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks @ddrondo and @timgraham

@timgraham timgraham merged commit d4748bf into mongodb:main Oct 7, 2025
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants