django models.py를 통해 테이블을 자동생성(마이그레이션)하면, 테이블 이름 규칙이 {{app이름}}_{{class이름}}으로 보기 좋지 않게 설정된다.
이를 {{prefix}}_{{class이름}}으로 보기좋게 변경할 수 있도록,
DB table에 prefix를 일괄적용하는 코드를 작성하는 방법은 아래와 같다.
from django.db import models
class BaseModel(models.Model):
class Meta:
abstract = True
db_table = None # Initialize db_table
def __init_subclass__(cls, **kwargs) -> None:
super().__init_subclass__(**kwargs)
cls.Meta.db_table = f"{{prefix}}_{cls.__name__.lower()}"
from django.db import models
from django.contrib.auth.models import User
from config.models import BaseModel
# Create your models here.
class Post(BaseModel):
user = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='posts')
question = models.CharField(max_length=200)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)