Django

Natural Key example Link to heading

+class MyModelManager(models.Manager):
+    def get_by_natural_key(self, field1, field2):
+        return self.get(field1=field1, field2=field2)
+
+
 class MyModel(models.Model):
     created_at = models.DateTimeField(auto_now_add=True)
     updated_at = models.DateTimeField(auto_now=True)
     field1 = models.CharField(max_length=254)
     field2 = models.CharField(max_length=254)
+
+    objects = MyModelManager()
+
+    def natural_key(self):
+        return (self.field1, self.field2)

Template Link to heading

Adding a char when the for loop has next element Link to heading

{% for x in tool.lists.all %}
    {{ x }}{% if not forloop.last %},{% endif %}
{% endfor %}

Testing Link to heading

Unmanaged models Link to heading

# conftest.py
def pytest_sessionstart():
    from django.apps import apps

    unmanaged_models = [m for m in apps.get_models() if not m._meta.managed]

    for m in unmanaged_models:
        m._meta.managed = True

# pyproject.toml
[tool.pytest.ini_options]
addopts = "--no-migrations"

Defining a conftest shared between all apps Link to heading

The conftest.py must be in the same directory of manage.py.

TestCase vs TransactionTestCase Link to heading

TestCase Link to heading

  • is faster than TransactionTestCase
  • doesn’t commit the changes
  • runs each test inside a transaction to provide isolation
  • wraps the tests within two nested atomic(): 1. whole class; 2. each test.
  • doesn’t truncate tables after a test. Instead, it encloses the test code in a database transaction that is rolled back at the end of the test

References: Writing and running tests | Django documentation, TestCase | Django documentation, TestCase | django/django/test/testcases.py, pytest.mark.django_db | pytest-django/pytest_django/fixtures.py

TransactionTestCase Link to heading

  • resets the database after the test runs by truncating all tables
  • may call commit and rollback

References: TransactionTestCase | Django documentation, TransactionTestCase | django/django/test/testcases.py, pytest.mark.django_db | pytest-django/pytest_django/fixtures.py

virtual_only fields Link to heading

Toolbox Link to heading

Moved to My Toolbox:

Multi-tenancy Link to heading