2 minute read

ORM

#sql #sqlite #django #객체지향

1. orm 정의

Object - Relational - Mapping

객체 지향 프로그래밍 언어를 사용하여 호환되지 않는 유형의 시스템 간의 데이터를 변환하는 기술

Django 프레임워크는 내장 Django ORM을 활용

2. 실습 환경 설정

아래 명령어는 모두 터미널에서 수행해주세요.

가상환경

  • 생성
python -m venv venv
  • 실행

    • windows
    . venv/Scripts/activate
    
    • mac
    . venv/bin/activate
    
  • 확인

    • 실행 전

    img

    • 실행 후, 경로 위 혹은 왼쪽에 가상환경 이름 출력

    img

  • 종료

deactivate

패키지 설치

아래의 모든 명령어는 가상환경을 실행한 상태로 진행하세요.
  • 가상환경 실행

    • windows
    . venv/Scripts/activate
    
    • mac
    . venv/bin/activate
    
  • pip install

pip install -r requirements.txt 
  • django 패키지 설치 확인
python manage.py --version
# 4.0.6

모델 마이그레이션

python manage.py makemigrations

python manage.py migrate

django shell

  • shell 진입
python manage.py shell_plus
  • 진입 확인

img

파일 실행

파일을 실행할 때에는 가상환경을 실행한 상태인지 꼭 확인합니다.
python main.py

License

The MIT License (MIT) Copyright (c) 2022 Dan Caron

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

3. Migration(마이그레이션)

  • Model에 생긴 변화를 DB에 반영하기 위함

  • 마이그레이션 파일을 만들어 DB스키마를 반영

  • 명령어

    • makemigrations : 마이그레이션 파일 생성
    • migrate : 마이그레이션을 DB에 반영
    $ python manage.py makemigrations
    $ python manage.py migrate
    

4. 데이터베이스 조작(Database API)

Genre. objects. all ( )

Class Name Manager QuerySet API

5. ORM 기본 조작

  • Create

    # 1. create 메서드 활용
    Genre.objects.create(name='발라드')
      
    # 2. 인스턴스 조작
    genre = Genre()
    genre.name = '인디밴드'
    genre.save()
    
  • Read

    # 1. 전체 데이터 조회
    Genre.objects.all()
    # <QuerySet [<Genre: Genre object (1)>, <Genre:Genre object (2)>]>
      
    # 2. 일부 데이터 조회(get)
    Genre.objects.get(id=1)
    # <Genre: Genre object (1)>
      
    # 3. 일부 데이터 조회(filter)
    Genre.objects.filter(id=1)
    # <QuerySet [<Genre: Genre object (1)>]>
    
  • Update

    # 1. genre 객체 활용
    genre = Genre.objects.get(id=1)
      
    # 2. genre 객체 속성 변경
    genre.name = '트로트’
      
    # 3. genre 객체 저장
    genre.save()
    
  • Delete

    # 1. genre 객체 활용
    genre = Genre.objects.get(id=1)
      
    # 2. genre 객체 삭제
    genre.delete()
    

Updated: