Maxima's Lab

[Django] Database (데이터 베이스) 구축 및 연동(Models, Connection) 본문

Web Programming

[Django] Database (데이터 베이스) 구축 및 연동(Models, Connection)

Minima 2023. 1. 8. 12:00
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
Comments