About Accessing Django Project Code from a Python Script

The minimal setup required to access Django models from a Python script is to set the DJANGO_SETTINGS_MODULE environment variable and then call django.setup():

import os
import django

os.environ.setdefault(
    "DJANGO_SETTINGS_MODULE", "myproject.settings.local"
)
django.setup()

from django.contrib.auth.models import User
print(
    "Active users:",
    User.objects.filter(is_active=True).count()
)

Alternatively and preferably, create a Django management command instead.

Tips and Tricks Programming Django 6.x Django 5.2 Django 4.2 Python 3