ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [파이썬] Database - Django model, model 사용법, api 사용
    º Language º/Python 2023. 10. 7. 20:20

     

    앱을 만들 때 데이터를 저장하기 위해 데이터 베이스가 필요합니다.

     

    ORACLE 데이터 베이스를 사용해보겠습니다.

     

    0. django에서 Oracle 연동하기 위해 필요한 모듈입니다. "cx_Oracle" 모듈을 받아줍니다.

    pip install cx_Oracle

     

    1. settings.py 에서 DATABASES 를 변경해줍니다.

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.oracle',
            'NAME': 'SID',  // xe
            'USER': '유저ID',
            'PASSWORD': '비밀번호', 
            'HOST': '호스트',  // 'localhost'
            'PORT': '1521',
        }
    }

     

    2. 데이터베이스에서 테이블을 만드는 명령을 실행합니다.

    (myenv) C:\work\mysite>py manage.py migrate
    Operations to perform:
      Apply all migrations: admin, auth, contenttypes, sessions
    Running migrations:
      Applying contenttypes.0001_initial... OK
      Applying auth.0001_initial... OK
      Applying admin.0001_initial... OK
      Applying admin.0002_logentry_remove_auto_add... OK
      Applying admin.0003_logentry_add_action_flag_choices... OK
      Applying contenttypes.0002_remove_content_type_name... OK
      Applying auth.0002_alter_permission_name_max_length... OK
      Applying auth.0003_alter_user_email_max_length... OK
      Applying auth.0004_alter_user_username_opts... OK
      Applying auth.0005_alter_user_last_login_null... OK
      Applying auth.0006_require_contenttypes_0002... OK
      Applying auth.0007_alter_validators_add_error_messages... OK
      Applying auth.0008_alter_user_username_max_length... OK
      Applying auth.0009_alter_user_last_name_max_length... OK
      Applying auth.0010_alter_group_name_max_length... OK
      Applying auth.0011_update_proxy_permissions... OK
      Applying auth.0012_alter_user_first_name_max_length... OK
      Applying sessions.0001_initial... OK

     

    3. polls / models.py  파일을 수정하여 다음과 같이 두 개의 모델을 만드는 코드를 작성합니다.

    - 연습을 위해 만들고 있는 간단한 설문조사(poll)을 위해 Question과 Choice 라는 두 개의 모델을 만듭니다.

    from django.db import models
    
    # Create your models here.
    class Question(models.Model):
        question_text = models.CharField(max_length=200) // 설문조사 문제
        pub_date = models.DateTimeField('date published') // 날짜
    
    class Choice(models.Model):
        question = models.ForeignKey(Question, on_delete=models.CASCADE) // Question FK
        choice_text = models.CharField(max_length=200) // 선택 답변
        votes = models.IntegerField(default=0) // 투표 결과 수

    * question = models.ForeignKey(Question, on_delete=models.CASCADE)

       -  ForeignKey(Question,  :  Question 모델을 참조하여 외래키(FK)로 받아옵니다.

       -  on_delete=models.CASCADE) Question이 삭제 될 때 함께 삭제 됩니다.

     

     

    4. 앱을 현재의 프로젝트에 포함 시키기 위해, 앱의 구성 클래스에 대한 참조를 INSTALLED_APPS 설정에 추가합니다.

    - PollsConfig 클래스는 polls/apps.py 파일 내에 존재하기에 'polls.apps.PollsConfig'를 추가합니다.

    # Application definition
    
    INSTALLED_APPS = [
        'polls.apps.PollsConfig'
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]

    - 이제, Django는 polls 앱이 포함되는 것을 알게 되었습니다. 

     

     

    5. makemigrantions 명령어를 수행합니다.

    - 이전에 작성한 모델( Question과 Choice )을 데이터베이스에 적용하기 위해, 데이터베이스 내에 테이블을 생성할 수 있도록 설계도를 만들기 위한  '마이그레이션 작업'을 수행하겠습니다.

    (myenv) C:\work\mysite>py manage.py makemigrations polls
    Migrations for 'polls':
      polls\migrations\0001_initial.py
        - Create model Question
        - Create model Choice

    polls\migrations\0001_initial.py 생성된것을 확인할 수 있습니다.

     

    더보기

    오류 1

    DPI-1047 Cannot locate a 64-bit Oracle Client library 오류 

    django.db.utils.DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library: "The specified module could not be found". See https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html for help

    해당 오류는 Oracle Client의 경로를 찾지 못해서 발생하는 오류 입니다.

     

    아래 링크를 통해 설치 가능합니다.

    https://www.oracle.com/kr/database/technologies/instant-client/winx64-64-downloads.html

     

    Django를 실행했을 때 시스템에서 해당 경로를 자동으로 인식할 수 있게끔 Windows 환경에서는 Path에 등록해주면 됩니다.

    내 컴퓨터 우클릭 > 고급 시스템 설정 > 환경 변수 > 시스템 환경 변수 편집 

     

    환경변수를 설정해주고 사용하던 터미널이나 IDE에서 그래도 똑같이

    django.db.utils.DatabaseError: DPI-1047: Cannot locate a 64bit Oracle Client library: "The specified module could not be found". See https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html for help

    오류가 발생하는 경우가 있습니다.

     

    사용하던 터미널이나 IDE를 재시작해주고 서비를 실행하면 정상적으로 실행될 것 입니다.

     

     

    오류 2

    error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ 
    Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output]

    오류 메시지에 따르면 cx_Oracle 패키지를 빌드하는 동안 Microsoft Visual C++ 14.0 이상 버전이 필요하다고 나와 있습니다. cx_Oracle는 C 확장 모듈로, 컴파일되어야 하기 때문에 컴파일러가 필요합니다. 이를 해결하기 위해서는 다음 단계를 따르세요:

    1. Visual C++ 빌드 도구 설치: 오류 메시지에 나와 있는 링크인 "Microsoft C++ Build Tools"에서 Visual C++ 14.0 이상 버전의 빌드 도구를 설치하세요. 이 빌드 도구는 컴파일러와 관련된 것들을 포함하고 있습니다.설치 중에 "Desktop development with C++" 옵션을 선택하고 설치하세요.
    2. 다음 링크에서 Microsoft C++ 빌드 도구를 다운로드할 수 있습니다: Microsoft C++ Build Tools
    3. 설치 재시도: 빌드 도구를 설치한 후에 다시 cx_Oracle 패키지를 설치해보세요:

     

    6. 데이터베이스에 실제 테이블을 생성하는 작업을 수행합니다.

    (myenv) C:\work\mysite>py manage.py migrate

     

    - 오라클 디벨로퍼에 연결하여 테이블을 확인하면 데이터가 생성된 것을 확인하실 수 있습니다.

     


    * api 가지고 놀기 

    - api란?

       개발자가 필요로 하는 데이터를 뽑아낼 수 있도록 만들어 놓은 함수

       데이터베이스에게 데이터를 입력할 수 있도록 만들어 놓은 함수

     

    1. 대화식 Python 쉘에 뛰어들어 Django API를 자유롭게 가지고 놀아봅시다.

    (myenv) C:\work\mysite>py manage.py shell

    2. Choice 모델과 Question 모델을 사용할 수 있도록 합니다.

    >>> from polls.models import Choice, Question

    3. Question 모델에서 사용 가능한 모든 데이터를 가져오라는 명령어를 작성합니다.

    - 아직 데이터가 없기에 [] 빈 값이 출력됩니다.

    >>> Question.objects.all()
    <QuerySet []>

    4. Question 모델에 데이터를 추가하겠습니다. 

    - 날짜가 들어가기에 timezone 라이브러리를 import 해줍니다.

    - 데이터를 넣어주고, save() 해줍니다. 

    - q.id : id 값이 1이 나왔습니다, 이는 장고에서 모델 생성시 자동으로 만들어주는 필드 중 하나입니다.

    >>> from django.utils import timezone
    >>> q = Question(question_text="What's new?", pub_date=timezone.now())
    >>> q.save()
    >>> q.id
    1

    5. 결과

    >>> q.question_text
    "What's new?"
    >>> q.pub_date
    datetime.datetime(2023, 10, 5, 20, 59, 43, 353441, tzinfo=datetime.timezone.utc)
    
    >>> Question.objects.all() // 오브젝트 개수 확인
    <QuerySet [<Question: Question object (1)>]>

    => [<Question: Question object (1)>] 이러한 오브젝트 개수 확인은 별로 도움이 되지 않습니다. 

    Question  모델을 수정하여, __str__() 메소드를 Questionrhk Choice에 추가해봅니다.

    import datetime
    from django.db import models
    from django.utils import timezone
    
    # Create your models here.
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
    
        def __str__(self):
            return self.question_text
        
        def was_published_recently(self):
            return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
        
    
    class Choice(models.Model):
        question = models.ForeignKey(Question, on_delete=models.CASCADE)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)
    
        def __str__(self):
            return self.choice_text

    - 변경된 코드로 인하여 결과값이 객체의 개수 1 이 아닌 해당 데이터가 출력됩니다.

    (myenv) C:\work\mysite>py manage.py shell
    >>> from polls.models import Choice, Question
    >>> Question.objects.all()
    <QuerySet [<Question: What's new?>]>
Coder yein