๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Python/ETC

[Django] ์žฅ๊ณ  MySQL ์—ฐ๋™ ์ฒ˜๋ฆฌ :: ๋งˆ์ด์ž๋ชฝ

by ๐ŸŒปโ™š 2019. 4. 7.

์žฅ๊ณ  MySQL ์—ฐ๋™

Default๋กœ sqlite๋ฅผ MySQL๋กœ ๋ณ€๊ฒฝํ•˜๊ณ ์ž ํ•œ๋‹ค.

์‚ฌ์ „์— MySQL์€ ๋‹น์—ฐํžˆ ์„ค์น˜๊ฐ€ ๋˜์–ด ์žˆ์–ด์•ผํ•˜๊ณ  ๊ฐ€์ƒํ™˜๊ฒฝ์— ์ ‘์†ํ•˜์—ฌ pip๋ฅผ ํ†ตํ•ด mysqlcilent๋ฅผ ๋ฐ›๋Š”๋‹ค.

pip install mysqlclient

 

settings.py

์ดํ›„ settings.py์˜  DB์„ค์ • ๋‚ด์šฉ์„ ๋ณ€๊ฒฝํ•ด์ฃผ์–ด์•ผํ•œ๋‹ค.

ํ•ด๋‹น ๋‚ด์šฉ์€ django_test ์ด๋ฆ„์˜ db์— jamong์œ ์ €๊ฐ€ ์ ‘๊ทผํ•œ๋‹ค๋Š” ๋‚ด์šฉ์ด๋‹ค.

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_test',
        'USER': 'jamong',
        'PASSWORD': '๋น„๋ฐ€๋ฒˆํ˜ธ',
        'HOST': 'localhost',
        'PORT': '3306',
        'OPTIONS': {
            'init_command': 'SET sql_mode="STRICT_TRANS_TABLES"'
        }
    }
}

 

models.py

์žฅ๊ณ ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด์„œ ๊ฐ€์žฅ ํฐ ์žฅ์  ์ค‘ ํ•˜๋‚˜๊ฐ€ ํ”„๋ ˆ์ž„์›Œํฌ ์ƒ์—์„œ DB์ œ์–ด๊ฐ€ ์‰ฝ๊ฒŒ ๊ฐ€๋Šฅํ•˜๋‹ค.

CRUD์˜ ๋ชจ๋“  ๋‚ด์—ญ์„ ์ฝ”๋“œ์ƒ์œผ๋กœ ๊ตฌํ˜„ํ•˜์ง€ ์•Š๊ณ  ํ”„๋ ˆ์ž„์›Œํฌ์—์„œ ์ œ๊ณตํ•ด์ฃผ๋Š” ๋„๊ตฌ๋ฅผ ์ด์šฉํ•ด์„œ ์‹คํ–‰์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

๋‹จ,  Create์˜ ๊ฒฝ์šฐ models.py ํŒŒ์ผ์— ์ƒ์„ฑํ•  DB์˜ ๋ชจ๋ธ์„ ๋งŒ๋“ค์–ด ์ฃผ์–ด์•ผํ•œ๋‹ค.

__str__ ํ•จ์ˆ˜๋กœ ๊ด€๋ฆฌ์ž ํŽ˜์ด์ง€์— ์ถœ๋ ฅ ๋  ๋‚ด์šฉ์„ ์„ค์ •ํ•ด์ค€๋‹ค.

from django.db import models

# Create your models here.
class Furits(models.Model):
    name = models.CharField(max_length=50)
    descript = models.TextField()
    price = models.FloatField()
    quantity = models.IntegerField()
    cdate = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return [self.id ,self.name, self.descript]

 

๋ชจ๋ธ์„ ์ ์šฉํ•ด์ฃผ๊ธฐ ์œ„ํ•ด ์žฅ๊ณ  ๋ช…๋ น์–ด๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

./manage.py makemigrations first_app
./manage.py migrate

Fruits๋ผ๋Š” ๋ชจ๋ธ์ด ์ƒ์„ฑ๋˜๊ณ  ๋ฐ˜์˜๋˜๋Š” ๊ฒƒ ๊นŒ์ง€ ํ™•์ธํ–ˆ๋‹ค.

 

admin ๊ด€๋ฆฌ

์žฅ๊ณ  ํ”„๋ ˆ์ž„์›Œํฌ์—์„œ admin ๊ด€๋ฆฌ์ž ํŽ˜์ด์ง€์—์„œ DB์ œ์–ด๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค.

๊ด€๋ฆฌ์ž ํŽ˜์ด์ง€ ์ ‘์†ํ•˜๊ธฐ ์œ„ํ•ด superuser๋ฅผ ๋งŒ๋“ค์–ด ์ฃผ์–ด์•ผํ•œ๋‹ค.

./manage.py createsuperuser

 

admin.py

admin ํŽ˜์ด์ง€์— Fruits ๋ชจ๋ธ์„ ์ œ์–ดํ•  ์ˆ˜ ์žˆ๋„๋ก ์ถœ๋ ฅํ•ด์ฃผ๊ธฐ ์œ„ํ•ด admin.py๋‚ด์šฉ์— ์ถ”๊ฐ€ํ•œ๋‹ค.

from django.contrib import admin
from first_app.models import *

# Register your models here.
admin.site.register(Furits)

 

์‹คํ–‰ ๋ฐ ํ™•์ธ

์„œ๋ฒ„ ์‹คํ–‰ ํ›„

./manage.py runserver

127.0.0.1:8000/admin์œผ๋กœ ์ ‘์†ํ•œ๋‹ค.

๋กœ๊ทธ์ธ ์ ˆ์ฐจ๋ฅผ ๋๋‚ด๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด  Fruits DB์ œ์–ด๋ฅผ ํ•  ์ˆ˜ ์žˆ๋‹ค.

๋Œ“๊ธ€