iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🎩

Checking ID Allocation Status for All Tables in Django

に公開

Just a quick tip 🍣

This is a script to easily check the status of ID assignment for the default id fields in Django models.
It iterates through all fields of all models and outputs Model.objects.latest(*fields) if an AutoField is found.

https://docs.djangoproject.com/en/4.2/ref/models/querysets/#latest

Since this script doesn't handle SQL directly, I believe it will yield similar results for both MySQL and PostgreSQL.
However, with this implementation, if the latest ID has been deleted, the current assignment position may appear lower than it actually is. If you want to check the exact remaining capacity, you might want to consider using something like SHOW TABLE STATUS instead.

https://dev.mysql.com/doc/refman/8.0/ja/show-table-status.html

Start a REPL using python manage.py shell or similar, and run the following script.
Please run this in a production environment at your own risk 🐘

def describe_remaining_id_length():
    import django.apps
    from django.db.models import AutoField, BigAutoField, SmallAutoField
    results = []
    print('Iterate all Models', end="")
    for model in django.apps.apps.get_models():
        model_name = model.__name__
        for field in model._meta.get_fields():
            if isinstance(field, AutoField):
                field_name = field.name
                try:
                    latest_model = model.objects.latest(field_name)
                    latest_id = getattr(latest_model, field_name)
                except model.DoesNotExist:
                    latest_id = 0

                if isinstance(field, BigAutoField):
                    int_max = 9_223_372_036_854_775_807
                elif isinstance(field, SmallAutoField):
                    int_max = 32_767
                else:
                    int_max = 2_147_483_647

                field_type_name = type(field).__name__
                remaining = int_max - latest_id

                results.append({
                    'model_name': model_name,
                    'field_name': field_name,
                    'field_name_type': field_type_name,
                    'latest_id': latest_id,
                    'remaining': remaining,
                })
                print(".", end="")
    print('')
    print('')
    results = sorted(results, key=lambda x: x['remaining'])

    print('model_name,field_name,field_name_type,latest_id,remaining')
    for result in results:
        print(f"{result['model_name']},{result['field_name']},{result['field_name_type']},{result['latest_id']},{result['remaining']}")


describe_remaining_id_length()

Here is an example of the output:
The table is sorted in ascending order of the remaining column (available IDs).

Iterate all Models.......................

model_name,field_name,field_name_type,latest_id,remaining
HogeModel,id,AutoField,474505342,1672978305
FugaModel,id,AutoField,390425574,1757058073
...
PiyoModel,id,BigAutoField,72555344,9223372036782220463

That's all 😌

Discussion