TIL 46. Model과 migration 흐름 정리(ORM)

rahula·2021년 6월 30일
1

django

목록 보기
5/5
post-thumbnail

django model과 테이블의 관계에 대해 공부한 것들을 기록합니다. 이 글은 django공식문서engineertodeveloper을 토대로 합니다.

Model

Model이란?

Django web applications access and manage data through Python objects referred to as models. Models define the structure of stored data, including the field types and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc.

django 웹 어플리케이션은 모델에 의해 생성된 데이터를 접근하고 관리한다.
모델은 저장될 데이터의 구조를 정의한다. (필드의 타입, 글자의 사이즈, 디폴트값, 옵션 등등)

전체 흐름 : Model이 구조를 어떻게 정의하나?

모델의 각 attribute는 데이터베이스의 필드를 대표한다.

django에서 정의한 유저 모델.

mysql에 실제로 생성된 유저 테이블.

간단하게 설명하면, CharField 혹은 TextField면 캐릭터 즉 글자 타입의 필드가 되고, DateTimeField면 날짜 타입의 필드가 된다. 그렇게 여러 column을 가진 테이블을 만들 수 있다.

Fields

django 모델에서 가장 중요하고 유일하게 필수적인 것은 필드다.

각각의 필드는 적절한 Field 클래스의 instance여야만 한다.

Field로는 column의 타입을 정한다. 즉, 데이터베이스에게 어떤 종류의 데이터를 저장할 것인지 말하는 것.

Field options

각각의 Field는 Field에 맞는 특정한 인자값을 갖는다.

For example, CharField (and its subclasses) require a max_length argument which specifies the size of the VARCHAR database field used to store the data.

자주 쓰이는 option으로는 null, max_length, unique, auto_now등이 있다.

Automatic primary key fields

By default, Django gives each model an auto-incrementing primary key

django는 디폴트로 모든 테이블에 자동증가하는 pk id를 만들어준다. 그 내용은 다음과 같.

id = models.BigAutoField(primary_key=True)

If you’d like to specify a custom primary key, specify primary_key=True on one of your fields. If Django sees you’ve explicitly set Field.primary_key, it won’t add the automatic id column.

근데 왠만하면 django가 자동으로 만들어주도록 내버려두는게 편하지 않을까.

Meta options

Give your model metadata by using an inner class Meta, like so:

from django.db import models

class Ox(models.Model):
    horn_length = models.IntegerField()

    class Meta:
        ordering = ["horn_length"]
        verbose_name_plural = "oxen"
        db_table = "Oxes"

메타데이터는 데이터에 대해 설명하는 데이터이다. 그럼 여기선? 하나의 모델 인스턴스(테이블의 데이터)에 대해 설명하는 데이터라는 말이 된다.

Model metadata is “anything that’s not a field”, such as ordering options (ordering), database table name (db_table), or human-readable singular and plural names (verbose_name and verbose_name_plural). None are required, and adding class Meta to a model is completely optional.

ORM

ORM이 뭐야?

The Django ORM allows developers to interact with the database without writing any SQL. Instead, we write object-oriented Python code. The ORM automatically converts the Python code to SQL, a language that the database can understand.

django ORM은 파이썬의 언어와 객체(class)개념만을 이용해서 DB와 상호작용할 수 있는 방법이다. ORM은 파이썬 코드를 자동으로 DB가 이해할 수 있는 SQL문으로 변환해준다.

SQL 쿼리문에서 자유..?

One of the main benefits of an ORM is that it allows you to write python code instead of SQL—one less thing you have to learn as a developer. However, it’s essential to understand the mechanics of how it works.

전제조건 : Model class 상속

from django.db import models

class Recipe(models.Model):
    title = models.CharField(max_length=150)
    intro = models.TextField()

To create a data model for the ORM to map to the database, the python class must inherit from models.Model. Otherwise, the class would not be a data model for the ORM but rather a standard Python class.

각각의 모델은 ORM에 의해서 직접적으로 DB테이블에 매핑된다. 각각의 객체 즉 Class가 매핑되어 테이블이 되는 느낌. 여기서 모델의 attribute이 테이블의 column 혹은 field가 된다.

migration이란?

migration은 모델의 생성(혹은 변화)를 데이터베이스에 전달하기 위한 django의 방식이다. 이 과정에서 DB 스키마의 field를 생성하고, column을 바꾸고, 등등의 일이 일어난다.

makemigrations

makemigrations : 모델에 대해 만든 변화들을 기반으로 새로운 migration기준을 잡는 것. DB 스키마에 대한 버전 컨트롤 시스템으로 생각해야 한다. DB 스키마가 어떻게 변화해왔는지를 언젠가 알아야 하기 때문. git commit과 비슷한 개념.

You should think of migrations as a version control system for your database schema. makemigrations is responsible for packaging up your model changes into individual migration files - analogous to commits - and migrate is responsible for applying those to your database.

migration 파일.

What Django looks for when it loads a migration file (as a Python module) is a subclass of django.db.migrations.Migration called Migration. It then inspects this object for four attributes, only two of which are used most of the time:

  1. dependencies : a list of migrations this one depends on.
  2. operations : a list of Operation classes that define what this migration does. 가장 중요한 내용이 담긴다. 모델을 생성할지 삭제할지, 그리고 각각의 이름, 필드, 옵션들을 설정한다.

migrate

migrate : makemigrations로 만들어진 파일 내용을 DB에 적용. 여기서 실제적인 DB스키마의 변화가 일어난다. git push와 비슷한 개념.

migrate로 일어난 SQL문 예시

생각과 질문

  1. 흐름을 아니 참 좋다.
  2. migration이 버전컨트롤시스템이라면, 데이터베이스를 이전 migration버전으로 되돌리거나 병합도 할 수 있는 걸까?
  3. SQL문에 대해 알아보고 싶다.
profile
백엔드 지망 대학생

0개의 댓글