2017年11月30日木曜日

DjangoのModel使用

1)Modelを定義
appフォルダーにmodels.pyにTableとColumnを定義
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)

2)appをProjectに結び付く
settings.pyのINSTALLED_APPSにappを追加

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    .....

3)migrations作成
python manage.py makemigrations polls

4)migrate実施
python manage.py sqlmigrate polls 0001  #どんなSQL実行されるか確認
python manage.py migrate

Django appを作成

1)Projectを作成、cloud9環境ではすでに作成されたので、不要
django-admin startproject mysite

2)appを作成
python manage.py startapp polls

Projects vs. apps
What’s the difference between a project and an app? An app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.

3)Viewを作成
polls/views.py を編集

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

4)To call the view, we need to map it to a URL
 polls/urls.py を作成

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]

5)To point the root URLconf at the polls.urls module

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', admin.site.urls),
]

6)DBの設定
MySQLのアクセスモジュールを追加
sudo pip3 install PyMySQL

Projectフォルダーにsettings.pyのDATABASESを変更
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'c9',  #dbname
        'USER': 'XXXXc9',       #username
        'PASSWORD': 'password',
        'HOST': '',
        'PORT': '',
    }
}

manage.pyに以下を追加
import pymysql
pymysql.install_as_MySQLdb()

7)migrate実施
python manage.py migrate
settings.pyのINSTALLED_APPSに必要なTableが作成されれば、DB設定OK