250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- numpy
- FLASK
- yaml
- 딥러닝
- 웹 프로그래밍
- Web Programming
- 장고
- 컴퓨터 비전
- GUI
- k8s
- Deep Learning
- Docker
- 그래픽 유저 인터페이스
- tensorflow
- Tkinter
- 파이토치
- Python
- OpenCV
- Computer Vision
- pytorch
- 논문 리뷰
- 텐서플로우
- 데이터베이스
- paper review
- vue.js
- 파이썬
- Django
- MariaDB
- kubernetes
- POD
Archives
- Today
- Total
Maxima's Lab
[Django] Database (데이터 베이스) 구축 및 연동(Models, Connection) 본문
728x90
SMALL
안녕하세요, 오늘은 Django 내 Database (데이터 베이스)를 구축 및 연동하고 Shell을 사용하는 방법에 대해서 알아보겠습니다.
구현하기 위한 순차적인 절차는 다음과 같습니다.
- app 생성 (EX) App Name : "Appsample" & app 연동 Check
- "Appsample" directory 내 models.py & views.py & admin.py 파일 Check
"models.py" 파일 내 다음과 같이 구성해줍니다.
from django.db import models
#Create your models here.
class Modelpractice(models.Model):
Element_one = models.CharField(max_length=200)
Element_two = models.IntegerField(default=1)
Element_three = models.CharField(default="A", max_length=200)
Element_four = models.IntegerField(null=True)
Element_five = models.CharField(null=True, max_length=200)
def __str__(self):
return 'id : {}, Element_one : {}, Element_two : {}, Element_three : {}, Element_four : {}, Element_five : {}'.format(Element_one, Element_two, Element_three, Element_four, Element_five)
이어서, Appsample 디렉토리 내 admin.py 파일을 다음과 같이 구성해줍니다.
from django.contrib import admin
from Appsample.models import Modelpractice
#Register your models here
class ModelpracticeAdmin(admin.ModelAdmin):
list_disply = ('Element_one', 'Element_two', 'Element_three', 'Element_four', 'Element_five')
admin.site.register(Modelpractice, ModelpracticeAdmin)
이어서, Shell에서 다음과 같은 명령어를 입력해줍니다.
python manage.py migrate
python manage.py makemigrations
추가적으로 views.py 파일 내 위의 DB를 사용하는 코드에 대해서 알아보도록 하겠습니다.
from django.db import connection
from .models import Modelpractice
Entire_sql = "SELECT * FROM appsample_modelpractice"
Some_sql = "SELECT Element_two, Element_five FROM appsample_modelpractice"
Entire_cursor = connection.cursor()
Entire_cursor.execute(Entire_sql)
Entire_data = Entire_cursor.fetchall()
Some_cursor = connection.cursor()
Some_cursor.execute(SOme_sql)
Some_data = Some_cursor.fetchall()
위의 코드에서 Entire_sql은 Modelpractice Model 내 모든 구성요소를 불러오는 것이고, Some_sql은 Modelpractice Model 내 일부 요소들을 가지고 오는 것입니다.
지금까지, Django Project에서 데이터베이스를 구축하고 이를 views.py 파일에 연동시키는 방법에 대해서 알아보았습니다.
728x90
LIST
'Web Programming' 카테고리의 다른 글
[Database, DB] MariaDB 설치 방법 (Windows) (0) | 2023.10.04 |
---|---|
[Flask] Flask 설치 및 실행 방법 (Python Web Programming) (0) | 2023.09.21 |
[Django] App 생성 및 Project 연동 (0) | 2023.01.07 |
[Django] 가상 환경(Virtual Environment) 구축하기 - Mac Os (0) | 2022.11.12 |
[Django] HTML Form 사용법 (0) | 2022.11.03 |
Comments