본문 바로가기
Django

[Django] ORM과 DB 등록하기

by 기록하는_사람 2022. 12. 12.

ORM(Object-Relation Mapping)

📌 ORM(Object-Relation Mapping)

: 객체(Object)와 관계형 데이터베이스(Relational)를 연결(Mapping)하는 것.

  데이터베이스를 객체와 연결해 CRUD(Create Read Update Delete)할 때, SQL을 사용하지 않고 할 수 있음.

 

테이블 생성하기

📌 테이블 생성하기

① app 생성.

python manage.py startapp app이름

② app의 models.py에 table 생성.

# 예시) Student 테이블 생성.
from django.db import models

# Create your models here.
class Student(models.Model):  # table 사용하기 위해서는 models.Model을 상속받아야 함.
    name = models.CharField(max_length=30)  # 필드의 속성 부여.
    age = models.IntegerField()
    comment = models.TextField()

💡 models.CharField()를 사용할 때는 max_length를 설정해 줘야 함.

 

💡 레코드 이름 설정하기

# 예시) Student 테이블 생성.
from django.db import models

# Create your models here.
class Student(models.Model):  # table 사용하기 위해서는 models.Model을 상속받아야 함.
    name = models.CharField(max_length=30)  # 필드의 속성 부여.
    age = models.IntegerField()
    comment = models.TextField()
    
    def __str__(self):  # 레코드 이름 설정
    	return f"{self.age}세 {self.name}"

 

DB 등록하기

📌 DB 등록하기

① config/settings.py에 app 등록.

...
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app이름.apps.app이름(맨 앞 대문자)Config'
]
...

 

② 등록된 테이블을 DB에 올림.

python manage.py makemigrations

③ 올라온 DB를 등록.

python mange.py migrate

 

DB CRUD

📌 DB CRUD

https://codingrecord2209.tistory.com/333

 

[Python/Django] python shell로 데이터 CRUD

가상 환경으로 python shell 실행하기 📌 가상 환경으로 python shell 실행하기 python manage.py shell 데이터 추가하기 📌 데이터 추가하기 // 'test' app의 Student 테이블 데이터 from test.models import Student st = Stu

codingrecord2209.tistory.com

 

댓글