알쓸전컴(알아두면 쓸모있는 전자 컴퓨터)

Django 모델 만들기 본문

Web /Django

Django 모델 만들기

백곳 2017. 8. 7. 22:56

모델 만들기 


모델은 DB와 python 클래스 변수를 연결해주는 작업 이라고 생각 됩니다. 


모델을 수정 하는것은 models.py 을 수정 하는것입니다. 


$ nano ~/mysite/polls/models.py


우리가 만드는 단순한 설문조사(poll) 앱을 위해 Question 과 Choice 라는 두개의 모델을 만들어 보겠습니다.

from django.db import models

# Create your models here.

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    
class Choice(models.Model):
     question = models.ForeignKey(Question, on_delete=models.CASCADE)
     choice_text = models.CharField(max_length=200)
      votes = models.IntegerField(default=0)

각 모델은 django.db.models.Model 이라는 클래스의 서브클래스로 표현됩니다. 

   example) 

class Question(models.Model) or class Choice(models.Model) 상속을 받아 서브 클래스로 받습니다. 


각 모델은 몇개의 클래스 변수를 가지고 있으며, 각각의 클래스 변수들은 모델의 데이터베이스 필드를 나타냅니다.

   example)  

question_text,pub_date, question ,choice_text ,votes 등 입니다. 


또한 models 들의 첫번째 인자는 사람이 읽기 좋은 형태의 데이터를 넣어 줍니다. (추후에 관리자 페이지에서 무슨 말인지 알수 있습니다. )


 이제 mysite/settings.py 에 들어가서 


INSTALLED_APPS = [

    'polls.apps.PollsConfig',

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

]


앱을 추가해 주도록 합니다. 


$ python manage.py makemigrations polls


Migrations for 'polls':

  polls/migrations/0001_initial.py

    - Create model Choice

    - Create model Question

    - Add field question to choice


을 실행 시켜 줍니다. 


$ ./manage.py sqlmigrate polls 0001

BEGIN;

--

-- Create model Choice

--

CREATE TABLE `polls_choice` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `choice_text` varchar(200) NOT NULL, `votes` integer NOT NULL);

--

-- Create model Question

--

CREATE TABLE `polls_question` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `question_text` varchar(200) NOT NULL, `pub_date` datetime(6) NOT NULL);

--

-- Add field question to choice

--

ALTER TABLE `polls_choice` ADD COLUMN `question_id` integer NOT NULL;

ALTER TABLE `polls_choice` ADD CONSTRAINT `polls_choice_question_id_c5b4b260_fk_polls_question_id` FOREIGN KEY (`question_id`) REFERENCES `polls_question` (`id`);

COMMIT;

다음과 같이 사용할 쿼리문들 보여 줍니다. 

이제 적용 시켜보겠습니다. 

$ python manage.py migrate

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Applying polls.0001_initial... OK



이제 실제로 적용 됬는지 DB를 보겠습니다.
 


위와 같이 실제로 연동이 되어 생겼습니다. 

모델을 만드는것은 3가지 단계를 생각 하면 됩니다. 

1.(models.py 에서) 모델을 변경합니다.

2.python manage.py makemigrations 을 통해 이 변경사항에 대한 migration 을 만드세요.

3.python manage.py migrate 명령을 통해 변경사항을 데이터베이스에 적용하세요.



이제 파이썬과 대화식으로 프로램을 작성하면서 실제 DB와 연동이 되는지 알아 보겠습니다. 


파이썬에서 대화식 으로 django를 사용하는 방법은 2가지 있습니다. 


매번 실행때 마다 

$ python manage.py shell


실행 하는 법과 


>>> import django

>>> import os

>>>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

>>> django.setup()


을 실행 하는 법이 있습니다. 


>>>from polls.models import Question, Choice

>>> from django.utils import timezone

>>> q = Question(question_text="What's new?", pub_date=timezone.now())

>>> q.save()

여기서는 question_text 는 "What's new?" 을 주었고 pub_date 는 현재 시간을 준다음에 

q.save() 로 저장을 해습니다. 

DB를 살펴 보겠습니다. 


보시다 시피 동기화가 되었습니다. 


다시 

>>>q.question_text = "What's up?"

>>> q.save()


변수에 값을 넣어 주면 


다음과 같이 연동이 됩니다. 


이것은 굉장히 강력한 기능인듯 합니다. 


이를 응용하여 모델 클래서 여러가지 다른 API 와 조합을 통해 추후에 강력하게 DB를 사용할수 있습니다. 


기본 개념은 이렇고 추후에 필요한 기능은 API 문서 또는 구글링을 통해 사용하면 될것 같습니다. 


좀더 상세한 설명및 예제를 보실분은 


https://django-document-korean.readthedocs.io/ko/master/intro/tutorial02.html


에서 좀더 궁금증을 해결하실수도 있습니다. 



'Web > Django' 카테고리의 다른 글

django 관리 사이트 poll app 셋팅  (0) 2017.08.08
django 관리자 생성하기  (0) 2017.08.08
Anaconda 가상환경 spyder IDE 적용  (0) 2017.08.07
Django 데이터 베이스 설정  (0) 2017.08.05
Django start app 만들기  (0) 2017.08.05
Comments