WIL #7 [Django] crud2

신승호·2021년 4월 23일
0

WIL

목록 보기
9/20

🤷 기간 : 2021.04.23 ~ 2021.04.23
🤷 자료 : https://www.notion.so/wecode/Django-C-R-U-D-1-e105b472f2cc4647a38305b343389de3
🤷 내용: SQL로 API가지고 놀아보기 ㅋㅎ


Database에 저장할 table을 만들어 보자

1, models.py에서 세팅

  • products/models.py에 들어가서 테이블을 위한 코드 class를 세팅하거라
from django.db import models

# Create your models here.
class Prodcut(models.Model):				# 클래스는 앞글짜 대문자로 하고, 단수형으로 하는게 좋다. (이거 오타 ..  ; ; 확인 조심)
    name = models.CharField(max_length = 20)
    price = models.IntegerField()
    update_at = models.DateTimeField(auto_now_add=True)
    create_at = models.DateTimeField(auto_now_add=True)

    class Meta:         
        db_table = "products"				# 소문자에 복수형으로 만들어 주는게 테이블이름 만드는 방법

2. models.py에 세팅한 코드 설계도를 만들어 보자

  • migrations 를 하는 것 = 설계도 만들어 저장 ~ !
`python manage.py makemigrations products`
  • 아래와 같이 뜰꺼고 products/migrations0001_initial.py가 생길 것이야
Migrations for 'products':
  products/migrations/0001_initial.py
    - Create model Prodcuts

3. 설계도도 있으니 이제 생성해야지 ?

  • migrate하는 것 = 생성 띠
  • 이건 manage.py파일이 있는 westarbucks_name디렉토리에서 하는 것
python manage.py migrate
  • 아래같이 뜰꺼고 apply 뜬 migration 보이죠 ? 다 되 었다 . !
Operations to perform:
  Apply all migrations: contenttypes, products, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying products.0001_initial... OK
  Applying sessions.0001_initial... OK

테이블 다 만들었다 .. ! 어디서 볼 수 있소 ?

-> mySQL로 들어가서 table을 확인 할 수 있소.

만들어 놓은 테이블을 구경해보자 . !

1. mySQL 입장

  • 먼저 입장 하자 !
mysql -u root -p
Enter password:				# 지정했던 Password 치자

2. 아까 만들었던 서버에 들어가자

  • 아까 만든거 기억하지 ? 아래 코드 써넣었던 것처럼 ?
create database 20th character set utf8mb4 collate utf8mb4_general_ci;
  • 글고,starbucks_name/my_settings.pyDATABASES20th해놓은 것도 기억하지 ?
  • 근데 신기한건 따로 prodcuts/models.py안에서 table 세팅을 위한 코드에서 database 이름인20th를 포함한 코드는 없당 ^^
    • models.py에서도 20th(database)에 table저장을 위해서 코드 어디엔가 20th을 걸어서 연결 시켜줄꺼같았는데 아니넹

3. models.py에서 연결해 놓은 table 보자 !

  • 먼저, 데이타 베이스에서 20th로 들어가자
show databases;
+--------------------+
| Database           |
+--------------------+
| 20th               |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.01 sec)
  • 20th database를 사용하자
use 20th
Database changed
  • 20th로 database 바뀌었고, 20th안에 있는 table들 뭐있는지 함 볼까
show tables;
+---------------------+
| Tables_in_20th      |		# 아래는 20th에 있는 table들 이다 ! ! 
+---------------------+
| django_content_type |		# django에서 알아서 자체적으로 만들어 놓은 것
| django_migrations   |		# django에서 알아서 자체적으로 만들어 놓은 것
| django_session      |		# django에서 알아서 자체적으로 만들어 놓은 것	
| products            |		# 내가 만들어 놓은 table(`models.py`파일 내 class meta안에 db_table = "prodcut" 로 이름 저장해 놓았즤 ?
+---------------------+
  • products table에 data를 보고싶네 ~
select * from products;
# 원래 요기에 값없어야 되는건데 값을 먼저 넣어놓았던거라 값이 보이지만 원래 초기에는 없다고 생각해
+----+-------+-------+----------------------------+----------------------------+
| id | name  | price | update_at                  | create_at                  |
+----+-------+-------+----------------------------+----------------------------+
|  1 | shins |    20 | 2021-04-23 09:23:21.974399 | 2021-04-23 09:23:21.974491 |
+----+-------+-------+----------------------------+----------------------------+
1 row in set (0.00 sec)
  • products table 설명을 좀 보고싶은데 어떻게 구성되어잇나 ?~
desc products;
+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| id        | bigint      | NO   | PRI | NULL    | auto_increment |
| name      | varchar(20) | NO   |     | NULL    |                |
| price     | int         | NO   |     | NULL    |                |
| update_at | datetime(6) | NO   |     | NULL    |                |
| create_at | datetime(6) | NO   |     | NULL    |                |
+-----------+-------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

mySQL엥서 나오는 것은 control+ z

table 세팅 했으니 내부 data 세팅하자

  • 내부 data 세팅을 위한 첫 단추는 shell에 들어가야해
python manage.py shell
  • 그리고, products/models.py에 세팅해둔 class Productimport하자
from products.models import Product
  • 이제 ! table에 데이터 넣어보자. !
Prodcut.object.create(name = 'shins', price = '20')	# 이름을 똑같이 두어도 수정이 아니라 걍 추가되는것임
Prodcut.object.create(name = 'shins', price = '30')
Prodcut.object.create(name = 'shins', price = '30')
  • 그리고 mySQL에서 값 잘 넣어졌나 함 보까 ?
+----+-------+-------+----------------------------+----------------------------+
| id | name  | price | update_at                  | create_at                  |
+----+-------+-------+----------------------------+----------------------------+
|  1 | shins |    20 | 2021-04-23 09:23:21.974399 | 2021-04-23 09:23:21.974491 |
|  2 | shins |    30 | 2021-04-24 07:42:23.883374 | 2021-04-24 07:42:23.883584 |
|  3 | shins |    30 | 2021-04-24 07:42:28.006681 | 2021-04-24 07:42:28.006822 |
+----+-------+-------+----------------------------+----------------------------+
3 rows in set (0.00 sec)

여기까지, 만들어 놓은 table 구경했고, 거기에다가 data값 잘 넣었다 !

오늘은 ~ 요까지 ~ !

profile
신승홉니다

0개의 댓글

관련 채용 정보