반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- Medium
- CentOS
- programmers
- solution
- 해시
- 알고리즘
- 리트코드
- 장고
- dfs
- dump
- python
- leetcode
- Spark
- Easy
- RecommendationSystem
- kibana
- 엘라스틱서치
- elasticsearch
- 프로그래머스
- Optimization
- 깊이우선탐색
- twosum
- 파이썬
- daspecialty
- 키바나
- Algorithm
- AWS
- 스파크
- ELK
- Django
Archives
- Today
- Total
Archive
[Django] Model Coding Overview (실습1) 본문
반응형
0. Overview
코딩순서
- models.py : 테이블 정의
- admins. py : 정의된 테이블 Admin화면에 표시
실행순서
- manage.py makemigrations : DB에 변경이 필요한 사항 추출
- manage.py migrate : DB에 변경사항 반영
- manage.py runserver
1. models.py
- Table을 하나의 Class 로 정의, Table의 Column은 Class의 변수로 매핑
- Table Class는 django.db.models.Model 클래스를 상속받아 정의, 각 Class 내 변수 타입도 Django에서 미리 정의된 Field Class를 사용 - Primary Key의 경우 Not NULL로 자동으로 Django 에서 생성된다
- Froeign Key의 경우 클래스만 지정하면 되며, 지정한 클래스의 ID변수를 가져온다. 이 때 Column 명은 _id 접미사가 붙어 생성된다
- __str__() 메소드를 통해 Admin사이트에서 테이블명을 보여줄 때 객체를 문자열로 표현한다
from django.db import models
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateField('date_published')
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete = models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
2. admins. py
- models.py에서 정의한 Class를 import 하고, register() 함수를 이용하여 Admin 사이트에 등록해 줄 수 있다
from django.contrib import admin
from polls.models import Question, Choice
# Register your models here.
admin.site.register(Question)
admin.site.register(Choice)
3. manage.py makemigrations / migrate
- 코드상의 DB에 관련된 변경된 사항을 실제 DB에 반영해주는 작업
- makemigrations 명령어를 통해, /polls/migrations 디렉토리 하위에 migrations 파일들이 생기고, migrate 명령어를 통해 DB에 실제 Table을 생성하게 된다
(venv) djangoProject % python3 manage.py makemigrations
Migrations for 'polls':
polls/migrations/0001_initial.py
- Create model Question
- Create model Choice
(venv) djangoProject % python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
Applying polls.0001_initial... OK
4. manage.py runserver
파이썬 웹 프로그래밍 - 3. Django 웹프레임워크
반응형
'------ Web ------ > Backend' 카테고리의 다른 글
[Django] Form (0) | 2022.07.03 |
---|---|
[Django] Template System (0) | 2022.06.28 |
[Django] Admin (0) | 2022.06.26 |
[Django] View / Template Coding Overview (실습2) (0) | 2022.06.26 |
[Django] 장고 기본개념 ( MVT / Structure / Project생성 / Application생성 ) (0) | 2022.06.19 |
Comments