How to Unit Test a Django Model with managed = False
Django
2018-02-05 08:02 (8 years ago)

In Django, when you set Meta: managed = False on a model, you may encounter the following error during unit tests from other apps when trying to perform operations like create():
django.db.utils.ProgrammingError: (1146, "Table 'your_app.your_model' doesn't exist")
This error often occurs when you attempt to test a model created using ./manage.py inspectdb.
In such cases,
Simplifying the Testing of Unmanaged Database Models in Django | Caktus Group
provides a workaround, but
you can also try the following in your your_app/tests/__init__.py:
import sys
if 'test' in sys.argv:
# For testing
from ..models import YourModel
YourModel._meta.managed = True
Writing this in tests/__init__.py should be sufficient.
Please rate this article (No signup or login required)
Currently unrated
Related posts
How to Fix Display Issues in Django Admin Inlines After Upgrading to 5.1
Return Login and Redirect Views by Hardcoding Social Account Provider in django-allauth (When Using AWS Cognito, etc.)
After Upgrading to Django 5 and Updating Dependencies, SSL: CERTIFICATE_VERIFY_FAILED Error Occurs When Sending Emails
The "first" and "second" Arguments of assertEqual in Django's Unit Tests are Actually "expected" and "actual"
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.
We look forward to discussing your development needs.