About Atomic Transactions and Background Tasks

When calling a background task from a view with atomic transaction that creates model instances, make sure that you use transaction.on_commit(). Otherwise, the background task might be executed before the instances are reachable.

This also applies for administration views.

from django.db import models, transaction
from .tasks import generate_post_preview

class Post(models.Model):
    # ...
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        transaction.on_commit(
            lambda: generate_post_preview(post_id=self.pk)
        )

Here generate_post_preview() is a Huey task.

Tips and Tricks Programming Databases Django 5.2 Django 4.2 Django 3.2 PostgreSQL MySQL SQLite Huey