2017年4月16日日曜日

gentoo+DjangoでOracle Database 11g につなぐ

DjangoからOracle DB 11gへつないでみる


べつにgentooじゃなくても繋げます、ただgentooでやりたかっただけです

DBコネクタcx_Oracleをいれる


mysql-pythonてきなDBコネクタcx_Oracleを入れておく、ebuild作っておきましたのどうぞ
ugui7 ~ # layman -a karky7
ugui7 ~ # emerge -pv dev-python/cx_oracle
lculating dependencies... done!
[ebuild  N f   ] dev-db/oracle-instantclient-basic-11.2.0.4::gentoo  ABI_X86="32 (64) (-x32)" 0 KiB
[ebuild  N    ~] dev-python/cx_oracle-5.3::karky7  USE="doc {-test}" PYTHON_TARGETS="python2_7 python3_4" 0 KiB
ugui7 ~ # emerge -pv dev-python/cx_oracle

最近の私のlaymanリポジトリは腐りつつあるのでご注意ください。ウケル

Djangoをセットアップ


Djangoは入れてあるものとします
settings.pyを書き換え
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.oracle',
        'NAME': 'orcl', # SIDに指定するやつ
        'USER': 'ALCHU',
        'PASSWORD': 'IICHIKO20',
        'HOST': '192.168.253.13',
        'PORT': '1521'
    },
}

modelを作成


model.py
from __future__ import unicode_literals
from django.db import models

class Blogpost(models.Model):
    id = models.BigIntegerField(primary_key=True)
    title = models.TextField()
    authorid = models.ForeignKey('Person', db_column='authorId')  # Field name made lowercase.

    class Meta:
        db_table = 'BlogPost'


class Person(models.Model):
    id = models.BigIntegerField(primary_key=True)
    name = models.TextField()
    age = models.BigIntegerField(blank=True, null=True)
    regdate = models.DateTimeField(blank=True, null=True)

    class Meta:
        db_table = 'Person'

DBマイグレーションする


modelからテーブルを作成する
~/Code/django_skel $ ./manage.py makemigrations
~/Code/django_skel $ ./manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: admin, contenttypes, auth, app1, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying app1.0001_initial... 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 sessions.0001_initial... OK
このあとPersonテーブルに適当にデータを突っ込む

開発サーバーで動かしてみる


~/Code/django_skel $ ./manage.py runserver


cx_Oracle入れるのに、oracle提供のバイナリが必要なのがちょっと面倒だけどとりあえずdjangoもOracle Databaseでもいけることが分かった今日この頃です。

0 件のコメント:

コメントを投稿