Django/inflearn

데이터 조회하기

곽수진 2022. 11. 2. 00:22
반응형

python manage.py startapp third : third라는 새로운 웹 앱을 생성

 

 

from django.urls import path
from . import views

urlpatterns = {
    path('list/', views.list, name="list")
}

third/urls.py 생성

 

 

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('first/', include('first.urls')),
    path('second/', include('second.urls')),
    path('third/', include('third.urls')),
    path('admin/', admin.site.urls),
]

▶ url이 충돌하지 않도록 firstdjango/urls.py를 수정

 

 

"""
Django settings for firstdjango project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
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/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-=&v14*#%e)$a-0&+k85e0w@c3jj5k-2ab$2^7=g_tpc_et)%(&'

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'first',
    'second',
    'third'
]

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 = 'firstdjango.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 = 'firstdjango.wsgi.application'


# Databasepost.
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

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


# Password validation
# https://docs.djangoproject.com/en/3.2/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/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Seoul'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

▶ settings.py의 INSTALLED_APPS를 수정해 새 웹 앱을 추가함

 

 

from django.shortcuts import render

# Create your views here.
def list(request):
    context = {

    }
    return render(request, 'third/list.html', context)

▶ third/views.py에 list 메소드를 추가

 

 

templates/third/list.html을 생성하고 서버 실행

 

 

from django.db import models

# Create your models here.
class Restaurant(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=200)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

third/models.py에 모델 추가

class Restaurant(models.Model) : Restaurant이라는 모델 정의

name = models.CharField(max_length=30) : name 필드를 정의하고 최대 글자수 30으로 선언

address = models.CharField(max_length=200) : address 필드를 정의하고 최대 글자수 200으로 선언

created_at = models.DateTimeField(auto_now_add=True) : 글 작성 시(이 모델의 데이터(레코드) 저장시) 생성 시각 정의

updated_at = models.DateTimeField(auto_now=True) : 저장된 레코드 수정시 수정 시각

 

 

python manage.py makemigrations

python manage.py migrate

: third 웹 앱을 DB에 적용

 

 

from third.models import Restaurant

Restaurant(name="Deli Shop", address="Gangnam").save()

▶ Restaurant(name="Korean Food", address="Gangbuk").save()

▶ Restaurant(name="Sushi", address="Gangbuk").save()

: 레스토랑 정보 3개 추가

Restaurant.objects.all().values() : 입력된 데이터 조회

 

 

Restaurant.objects.get(pk=1).name

Restaurant.objects.get(pk=2).address

: 하나의 오브젝트를 선택하기 위해 primary key 기준으로 get 메소드 사용

반응형

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

페이징하기  (2) 2022.11.04
데이터 필터링하기  (0) 2022.11.03
Django ORM 개요  (0) 2022.11.01
Model Form으로 데이터 저장하기  (0) 2022.10.31
Model Form 사용하기  (0) 2022.10.30