장고(Django) 개발: MVC 패턴, 모델(Model)

웨드_ |

MVC 패턴에서 Model 영역을 의미하며, 장고 모델은 DB 데이터를 정의하는 작업이다. ORM(Object-relational mapping) 지원으로 선언하는 클래스가 DB의 테이블과 완벽히 매칭된다.

  • 장고의 Model = Model
  • 장고의 View = Controller
  • 장고의 Template = View


장고(Django) 개발: 프로젝트 시작과 구성 포스팅에서 모델 영역만을 자세히 정리한 것이다.


작년에 장고(Django) 프레임워크로 프로젝트를 진행하면서 공부했던 개발 지식을 블로그에 다시 정리하려고 합니다. 개인 위키에 정리했던 것을 옮기는 수준이라, 친절한 설명은 기대하기 어렵고, 프로그래밍 언어와 파이썬 지식이 어느정도 있어야 이해할 수 있을 것입니다.


아래 내용들은 Django 1.6~1.7 버전을 기준으로하고, "쉽고 빠른 웹개발 Django"란 책에서 1/3, 공식 위키에서 1/3, 그리고 나머지는 구글링을 바탕으로 정리한 지식입니다. 말투가 존대와 반말이 섞여있어도 이해바랍니다 :)





1 모델 만들기

2 모델의 필드 타입과 필드 옵션

3 모델의 메타 옵션

4 모델 관련 주요 함수

5 모델 관련 주요 콘솔 명령




1 모델 만들기

models 패키지의 Model 객체를 상속받는 클래스가 하나의 DB 테이블을 의미하며, 특정 Field 클래스의 인스턴트로 생성되는 변수들이 해당 테이블의 한 필드가 된다.

필드 설정시, 필드 타입과 필드 옵션, 그리고 메타 옵션 등을 지정할 수 있다.

from django.db import models
 
class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    필드명 = modles.필드_타입(필드_옵션)
 
    class Meta:
        ordering = ["first_name"]
        메타_옵션

참고 : https://docs.djangoproject.com/en/1.6/topics/db/models/



2 모델의 필드 타입과 필드 옵션

필드 타입은 크게 일반 필드 타입과 관계 필드 타입으로 나뉘고, 각 필드 클래스들이 DB 필드의 성격을 나타낸다

일반 필드 타입과 옵션

일반 필드 타입
설명
class AutoField(**options)

 아래 링크 참고

class BigIntegerField([**options]) 
class BinaryField([**options]) 
class BooleanField(**options) 
class CharField(max_length=None[, **options]) 
class CommaSeparatedIntegerField(max_length=None[, **options]) 
class DateField([auto_now=False, auto_now_add=False, **options]) 
class DateTimeField([auto_now=False, auto_now_add=False, **options]) 
class DecimalField(max_digits=None, decimal_places=None[, **options]) 
class EmailField([max_length=75, **options]) 
class FileField(upload_to=None[, max_length=100, **options]) 
class FloatField([**options]) 
class ImageField(upload_to=None[, height_field=None, width_field=None, max_length=100, **options]) 
class IntegerField([**options]) 
class IPAddressField([**options]) 
class GenericIPAddressField([protocol=both, unpack_ipv4=False, **options]) 
class NullBooleanField([**options]) 
class PositiveIntegerField([**options]) 
class PositiveSmallIntegerField([**options]) 
class SlugField([max_length=50, **options]) 
class SmallIntegerField([**options]) 
class TextField([**options]) 
class TimeField([auto_now=False, auto_now_add=False, **options]) 
class URLField([max_length=200, **options]) 

참고 : https://docs.djangoproject.com/en/1.6/ref/models/fields/#field-types

관계 필드 타입과 옵션

관계 필드 타입
설명
class ForeignKey(othermodel[, **options]) 아래 링크 참고
class ManyToManyField(othermodel[, **options]) 
class OneToOneField(othermodel[, parent_link=False, **options]) 

참고 : https://docs.djangoproject.com/en/1.6/ref/models/fields/#module-django.db.models.fields.related

공통 필드 옵션

모든 필드에서 공통으로 사용할 수 있는 필드 옵션임.

필드 옵션
설명
null 아래 링크 참고
blank 
choices 
db_column 
db_index 
db_tablespace 
default 
editable 
error_messages 
help_text 
primary_key 
unique 
unique_for_date 
unique_for_month 
unique_for_year 
verbose_name 
validators 

참고 : https://docs.djangoproject.com/en/1.6/ref/models/fields/#field-options



3 모델의 메타 옵션

모델에 추가적인 정보 제공이나 기능을 수행할 수 있도록 하는 것이 메타 옵션이다.

메타 옵션
설명
abstract 아래 링크 참고
app_label 
db_table 
db_tablespace 
get_latest_by 
managed 
order_with_respect_to 
ordering 
permissions 
proxy 
select_on_save 
unique_together 
index_together 
verbose_name 
verbose_name_plural 

참고 : https://docs.djangoproject.com/en/1.6/ref/models/options/#available-meta-options



4 모델 관련 주요 함수

하나의 모델인스턴스 = 하나의 DB레코드와 같음

모델인스턴스 = 모델클래스('값')             # 레코드 생성 (메모리)
모델인스턴스.필드 = '값';                   # 레코드 변경 (메모리)
모델인스턴스.save()                         # 변경 이력을 실제로 반영 (DB)
모델인스턴스.delete()                       # 레코드
변수 = 모델클래스.objects.all()             # 전부 조회 (배열 반환)
변수 = 모델클래스.objects.get(필드=값)      # '필드=값' 조건 조회 (배열 반환)
변수 = 모델클래스.objects.count()           # 레코드 수
 
# 모데의 객체를 문자열로 출력하기 위한 메서드 선언
def __unicode__(self):
    return self.변수



5 모델 관련 주요 콘솔 명령

# 모델 변경 후, 실제 DB에 반영하려면,
python manage.py syncdb
 
# 모델의 SQL을 직접 확인하려면,
python manage.py sql 앱이름
 
# 모델 작업을 Shell에서 직접하려면,
python manage.py shell