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
'Django' 카테고리의 다른 글
[Python/Django] 관리자 계정 생성하기 (0) | 2022.12.12 |
---|---|
[Django] python shell로 데이터 CRUD (0) | 2022.12.12 |
[Django] HTML 파일로써 Client에게 응답 주기 (0) | 2022.12.12 |
[Django] path 및 앱 생성 명령어 (0) | 2022.12.06 |
[Django] Django 설치 및 프로젝트 시작 (0) | 2022.12.06 |
댓글