20200309 django multi db & auto_commit

2020. 3. 9. 22:02개발/Django

오늘 회사에서 multi db를 활용할 일이 있어 간단하게 문서들을 읽어보고 적용시켜봤다가 결국엔 무산되었다. 기록으로라도 남긴다. 

1.Multi DB

setting.py에서 databases에 관해 다음과 같이 입력한다.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': os.environ['DB_NAME'],
        'USER': os.environ['DB_USER'],
        'PASSWORD': os.environ['DB_PASS'],
        'HOST': os.environ['DB_HOST'],
        'PORT': os.environ['DB_PORT'],
    },
    'nameyouwant': {
    	'ENGINE': 'db_engine you want',
        'NAME': ~~~~~~~~,
        ....
}

위와 같이 설정을 하면 db와 관련된 행동을 할때 별다른 명령이 없으면 default인 db에 행동을 하게 되는 것이다.

그 다음, default가 아닌 db에 저장하고 싶은 table은 다음과 같이 따로 추가로 설정해준다.

class SomeTable(models.Model):
	...
    class Meta:
    	using = 'nameyouwant' #default가 아닌 db의 이름을 넣는다

그리고 default가 아닌 db를 추적하게끔 할 수 있는 router가 필요하다.

class DbNotDefaultRouter(object):
	def db_for_read(self, model, **hints):
		return getattr(model._meta, 'using', None)
	def db_for_write(self, model, **hints):
		return getattr(model._meta, 'using', None)
	def allow_relation(self, obj1, obj2, **hints):
		if getattr(obj1._meta, 'using', None) == getattr(obj2._meta, 'using', None):
        	return True 
        return None
	def allow_syncdb(self, db, model): 
    	if db == getattr(model._meta, 'using', 'default'): 
        	return True
        return None

  

위와 같은 class는 아무 file에나 넣어도 된다.(하지만 간결성과 보수유지성을 위해 적절한 곳에다 넣는게 좋을 것 같다.) 그리고 나서 다시 settings.py에 다음과 같이 입력한다.

DATABASE_ROUTERS = ['path.to.DBYouWantRouter']

multi db 활용할 준비 끝~

출처: http://stackoverflow.com/a/5757011/2050087, 

 

2. postgres connection에서 commit..!

sql에서 update, insert, delete와 같이 table을 직접 수정해야 하는 경우에 

with psycopg2.connect(~~~) as conn:
	with conn.cursor() as cur:
    	yield cur
    conn.commit()

위와 같이 connect.commit()을 처리해줘야 한다고 한다.

출처: http://seorenn.blogspot.com/2012/06/python-postgresql-psycopg2.html

'개발 > Django' 카테고리의 다른 글

20200429 Django와 rest-framework  (0) 2020.04.29
20200327 postgresql unnest  (0) 2020.03.27
20200308 django bulk update  (0) 2020.03.09
20200306 Django Migration Conflict관련  (0) 2020.03.06
1-1.Migration에 대하여..!  (0) 2020.02.09