본문 바로가기

Django

django7 - DB, multi-table (제조사, 상품 관리)

 

on_delete

참조 된 객체가 삭제 될 때 동작하는 코드이다. django에만 국한된 것은 아니며 SQL 표준이다.

예시에서 models.py에 작성했다.

참조 문서

https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.ForeignKey.on_delete

 

CASCADE

값이 삭제될 때 참조하는 모델 인스턴스(row)도 삭제된다.
PROTECT

값이 삭제될 때 삭제가 되지않도록 ProtectedError를 발생시킨다. 삭제하려면 수동으로 참조하는 모든 객체를 삭제해야 한다. 
SET_NULL

값이 삭제될 때 ForeignKeyField값을 null로 바꾼다. (null=True일 때만 가능하다)
SET_DEFAULT

값이 삭제될 때 default 값으로 바꾼다. (default값이 있을 때만 가능하다)

SET()

값이 삭제될 때 SET에 설정된 함수 등에 의해 설정된다. 
DO_NOTHING

값이 삭제될 때 아무런 행동을 취하지 않는다. 참조무결성을 해칠 위험이 있다.

 

 

프로젝트 생성 과정

 

-project
프로젝트생성
app 생성
templates 폴더 만들기
settings 에서 사용 app 작성, databases 수정, LANGUAGE_CODE,TIME_ZONE 수정

-DB
models 작성
migrations, app이름 입력
migrate
mariadb prompt에서 해당 db로 접속, show tables, desc 테이블명 으로 테이블이 잘 만들어 졌는지 확인
adimin 작성 - 관리자 화면이 필요할 때만 작성
Anaconda Prompt 에서 경로이동
계정생성 python manage.py createsuperuser
chrome admin 접속 http://127.0.0.1/admin/
로그인, 항목 추가
mariadb prompt에서 확인. select * from 테이블명

-views, templates
urls path 등록
views 함수 작성
templates 작성

 

 

예시 프로젝트 구조 및 코드

 

 

 

settings.py

INSTALLED_APPS에 만든 app 작성

DATABASES에 databases 정보 입력

LANGUAGE_CODE,TIME_ZONE 수정

"""
Django settings for django7_multi_tab project.

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

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--+ncm!h%lhtt$vuuhb1yf$t%uv*o-t@#nk2d4c=c(kw_eix%3_"

# 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",
    "sangpum",
]

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 = "django7_multi_tab.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 = "django7_multi_tab.wsgi.application"


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'sangpumdb',           # DB명 : db는 미리 작성되어 있어야 함.       
        'USER': 'root',                # 계정명 
        'PASSWORD': '123',             # 계정 암호           
        'HOST': '127.0.0.1',           # DB가 설치된 컴의 ip          
        'PORT': '3306',                # DBMS의 port 번호     
    }
}



# 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 = "ko-kr"

TIME_ZONE = "Asia/Seoul"

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"

 

 

models.py

on_delete, CASCADE는 상단의 정리글을 참고하면 좋다. 

from django.db import models

# Create your models here.
class Maker(models.Model):
    mname = models.CharField(max_length=10)
    tel = models.CharField(max_length=30)
    addr = models.CharField(max_length=50)
    
    class Meta:
        ordering = ('-id',)
    
    # id 값 대신 mname을 보여줌
    def __str__(self):
        return self.mname
    
class Product(models.Model):
    pname = models.CharField(max_length=10)
    price = models.IntegerField()
    maker_name = models.ForeignKey(Maker, on_delete=models.CASCADE)  # fk의 대상은 Maker의 pk

 

 

admin.py

from django.contrib import admin
from sangpum.models import Maker, Product

# Register your models here.
class MakerAdmin(admin.ModelAdmin):
    list_display = ('id','mname','tel','addr')
    
admin.site.register(Maker, MakerAdmin)


class ProductAdmin(admin.ModelAdmin):
    list_display = ('id','pname','price','maker_name')
    
admin.site.register(Product, ProductAdmin)

 

 

urls.py

from django.contrib import admin
from django.urls import path
from sangpum import views

urlpatterns = [
    path("admin/", admin.site.urls),
     
    path('', views.Main),
    path('list1', views.List1),
    path('list2', views.List2),
    path('list3', views.List3),
]

 

 

views.py

from django.shortcuts import render
from sangpum.models import Maker, Product

# Create your views here.
def Main(request):
    return render(request, 'main.html')


def List1(request):
    makers = Maker.objects.all()
    return render(request, 'list1.html', {'makers':makers})


def List2(request):
    products = Product.objects.all()
    pcount = len(products)
    return render(request, 'list2.html', {'products':products, 'pcount':pcount})
    

def List3(request):
    mid = request.GET.get("id")
    products =Product.objects.filter(maker_name=mid)
    pcount = len(products)
    return render(request, 'list2.html', {'products':products, 'pcount':pcount})

 

 

main.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
** 자료보기 ** <p/>
<a href="list1">상품 제조사 정보</a> 
<a href="list2">상품 정보</a> 
</body>
</html>

 

 

list1.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>제조사 목록</h2>
<table border="1">
   <tr><th>코드</th><th>제조사명</th><th>전화</th><th>주소</th></tr>
   {% for m in makers %}
   <tr>
      <td>{{m.id}}</td>
      <td><a href="list3?id={{m.id}}">{{m.mname}}</a></td>
      <td>{{m.tel}}</td>
      <td>{{m.addr}}</td>
   </tr>
   {% endfor %}
</table>
</body>
</html>

 

 

list2.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>제조사 목록</h2>
<table border="1">
   <tr><th>코드</th><th>상품명</th><th>가격</th><th>제조사</th></tr>
   {% for p in products %}
   <tr>
      <td>{{p.id}}</td>
      <td>{{p.pname}}</td>
      <td>{{p.price}}</td>
      <td>{{p.maker_name}}</td>
   </tr>
   {% endfor %}
   <tr>
   		<td colspan="4">건수 : {{pcount}}</td>
   </tr>
</table>
</body>
</html>

'Django' 카테고리의 다른 글

django project 과정 정리  (0) 2022.10.18
django8 - DB, 표, CRUD, 페이징  (0) 2022.10.18
django6 - Maria DB (방명록)  (0) 2022.10.17
django5 - DB  (0) 2022.10.17
django4 - session 예제(간이 쇼핑몰, 장바구니 기능)  (0) 2022.10.17