#conda 가상환경 목록
$ conda env list
# conda 가상환경 생성 python 버전 지정
$ conda create -n '가상환경 이름' python=3.8
# conda 가상환경 활성화
$ conda activate westarbucks
$ pip install django
# 이후에 MySQL server에 접속하기 위한 package
$ pip install mysqlclient
# mysql 부터 설치
$ django-admin startproject westarbucks
$ cd westarbucks
$ python manage.py startapp products
# mysql sever 실행 명령어
$ mysql.server start
# mysql 실행 명령어
$ mysql -u root -p
# mysql database 생성
mysql> create database "NAME" character set utf8mb4 collate utf8mb4_general_ci;
ALLOWED_HOSTS = ['*']
settings.py
admin, csrf, auth, middleware
urls.py
# after
from django.urls import path
urlpatterns = [
]
settings.py
DATABASES = {
'default' : {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DATABASE 명',
'USER': 'root',
'PASSWORD': 'DB접속용 비밀번호',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
from django.db import models
class Menu(models.Model):
name = models.CharField(max_length=45)
class Meta:
db_table = "menu"
class Category(models.Model):
menu = models.ForeignKey('Menu', on_delete=models.CASCADE)
name = models.CharField(max_length=45)
class Meta:
db_table = "category"
class Drink(models.Model):
name = models.CharField(max_length=100, null=True)
description = models.TextField(null=True)
category = models.ForeignKey('Category', on_delete=models.CASCADE, null=True)
class Meta:
db_table = "drink_and_product"
class Nutrition(models.Model):
drink = models.OneToOneField('Drink', on_delete=models.CASCADE, null=True)
one_serving_kcal = models.DecimalField(max_digits=6, decimal_places=2, null=True)
sodium_mg = models.DecimalField(max_digits=6, decimal_places=2, null=True)
saturated_fat_g = models.DecimalField(max_digits=6, decimal_places=2, null=True)
sugars_g = models.DecimalField(max_digits=6, decimal_places=2, null=True)
protein_g = models.DecimalField(max_digits=6, decimal_places=2, null=True)
caffeine_mg = models.DecimalField(max_digits=6, decimal_places=2, null=True)
class Meta:
db_table = "nutritions"
class Allergy(models.Model):
name = models.CharField(max_length=45, null=True)
class Meta:
db_table = "allergy"
class AllergyDrink(models.Model):
allergy = models.ForeignKey('Allergy', on_delete=models.CASCADE, null=True)
drink = models.ForeignKey('Drink', on_delete=models.CASCADE, null=True, related_name='+')
class Meta:
db_table = "allergy_drink"
class Image(models.Model):
image_url = models.URLField()
drink = models.ForeignKey('Drink', on_delete=models.CASCADE, null=True)
class Meta:
db_table = "images"
# from 'app 파일명'.models import '불러올 class'
>>> from products.models import *
# QuerySet Method로 data 입력 예시
>>> Menu.objects.create(name="음료")
>>> a1 = Menu(name="음료")
# ForeignKey 설정
>>> Category.objects.create(name="콜드브루" menu=a1)
>>> Category.objects.create(name="푸드" menu=a1)
mysql> show tables;
mysql> desc menu;
mysql> desc category;
mysql> desc drink_and_product;
mysql> desc allergy;
mysql> select * from menu;
mysql> select * from category;