Open2
Pythonのtips
djangoのモデルに対して、shell_plus上で以下コマンドで逆参照のフィールドなども調査できる
YourModel._meta.get_fields()
Djangoのすべてのモデルとフィールドを走査して、利用している最大のIDカラムとあとどのくらい採番可能かチェックするスクリプト
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']}")