본문 바로가기
개발일지/Django

Django - 데이터베이스 모델 연결하기

by 다니엘의 개발 이야기 2022. 9. 30.
320x100

이번에도 연결이 참 많다.

 

그리고 정말 이 강의 강추한다.

최고의 입문자 강의다.

함수와 클래스 기반의 django 개발자가 되면

개발 인생이 달라질거라고 하는데

암튼 지금은 잘 모르겠지만 정말 대단하다.

 

더불어서 아래의 코드는 처음부터 쌩으로 다 작성한 것도 있지만

보통 python manage.py ~~~ 로 이용되는 명령으로 생성 한 것들도 있다.

가장 중요한건 명령문과 순서인데, 그것까지 캐치하진 못했다.


# 첫번째 파일

my_site > office > models.py

from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator

# Create your models here.
class Patient(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    # 가장 낮은 값은 0, 가장 높은 값은 120으로 설정하겠다는 의다.
    age = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(120)])
    heartrate = models.IntegerField(default = 60, validators=[MinValueValidator(1), MaxValueValidator(300)])

    def __str__(self):
        
        return f'{self.last_name},{self.first_name} is {self.age} years old.'

# 두번째 파일

my_site > office > migrations > 0002_patient_heartrate_alter_patient_age.py

# Generated by Django 4.1.1 on 2022-09-30 09:54

import django.core.validators
from django.db import migrations, models


class Migration(migrations.Migration):

    # dependencies는 '의존성'이라는 의미다.
    dependencies = [
        ("office", "0001_initial"),
    ]

    operations = [
        migrations.AddField(
            model_name="patient",
            name="heartrate",
            field=models.IntegerField(
                default=60,
                validators=[
                    django.core.validators.MinValueValidator(1),
                    django.core.validators.MaxValueValidator(300),
                ],
            ),
        ),
        migrations.AlterField(
            model_name="patient",
            name="age",
            field=models.IntegerField(
                validators=[
                    django.core.validators.MinValueValidator(0),
                    django.core.validators.MaxValueValidator(120),
                ]
            ),
        ),
    ]

# 세번째 파일

my_site > office > urls.py

from django.urls import path
from . import views

# domain.com/office ---> list of all the patients
urlpatterns = [
    path('', views.list_patients, name = 'list_patients'),
]

# 네번째 파일

my_site > office > views.py

from django.shortcuts import render
from . import models

# Create your views here.

def list_patients(request):
    
    all_patients = models.Patient.objects.all()
    context = {'patients': all_patients}

    return render(request, 'office/list.html', context = context)

# 다섯번째 파일

my_site > office > templates > office > list.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>list.html</title>
</head>
<body>
    
    <ul>
    {% for person in patients %}
    
    <li>{{person.last_name}}</li>
    
    {% endfor %}
    </ul>

</body>
</html>

# 여섯번째 파일

my_site > my_site > urls.py

"""my_site URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path('office/', include('office.urls'))
]

# 일곱번째 파일

my_site > my_site > settings.py

"""
Django settings for my_site project.

Generated by 'django-admin startproject' using Django 4.1.1.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-p6!3&!!rcek@)xedwp*att0ac1p86)@)hap-uex&5!pz1nm@s_"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'office.apps.OfficeConfig',
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "my_site.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "my_site.wsgi.application"


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",},
    {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",},
    {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",},
]


# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = "static/"

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
300x250