Programming-[Backend]/Django
[TIL] django data migration 데이터 마이그레이션
컴퓨터 탐험가 찰리
2022. 12. 17. 21:04
728x90
반응형
https://simpleisbetterthancomplex.com/tutorial/2017/09/26/how-to-create-django-data-migrations.html
- 데이터베이스의 Schema를 변경하는게 아니라 data들을 조작할 수 있는 것을 Data Migrations라 한다.
- 새로운 필드를 추가하고 그 값을 넣고 싶으면 models.py에서 해당 필드를 null=True를 주거나 default값을 주고 schema변경 마이그레이션 적용 → data migration → null=False로 변경하는 순서를 적용해야한다.
- 빈 마이그레이션 파일을 만들고, 원하는 함수를 작성한 뒤 migrations.RunPython()안에 함수명을 적어주면 적용된다.
def **slugify_title**(apps, schema_editor):
'''
We can't import the Post model directly as it may be a newer
version than this migration expects. We use the historical version.
'''
Post = apps.get_model('blog', 'Post')
for post in Post.objects.all():
post.slug = slugify(post.title)
post.save()
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_post_slug'),
]
operations = [
migrations.RunPython(**slugify_title**),
]
- 생성할 함수의 인자값은 apps, schema_editor이며, schema를 변경하지 않으므로 apps.get_model만 사용하면 된다.
마이그레이션 reverse를 위해 옵션 넣기. noop은 아무것도 안한다는 뜻이며 데이터마이그레이션이라 noop으로 진행함
To allow backward migrations you can use dummy RunPython.noop as a reverse-function.
operations = [
migrations.RunPython(slugify_title, migrations.RunPython.noop),
]
728x90
반응형