프로그래밍/Python

Python 공부 노트 8. - Django 에서 model을 이용한 기본 데이타 베이스 프로그래밍

Terry Cho 2013. 1. 23. 21:05

Django는 기본적으로 MVC 모델을 가지고 있고, DB 접근에 대해서는 OR Mapper와 같은 기능을 model 기능을 이용해서 제공한다.  

사실 최적화 정도는 조금 고려해봐야 겠지만, 기본적인 사용 방법은 다음과 같다.


==

python manage.py syncdb

- setting.py를 참고로 하여, default table을 데이타베이스에 생성


python startapp {appname}

- 새로운 app을 생성함. 

- 생성후에는 setting.py에 가서, INSTALLED_APPS 부분에 생성한 app이름을 넣어줘야 컨테이너가 인식함

INSTALLED_APPS = (

   'django.contrib.auth',

   'django.contrib.contenttypes',

   'django.contrib.sessions',

   'django.contrib.sites',

   'django.contrib.messages',

   'django.contrib.staticfiles',

   # Uncomment the next line to enable the admin:

   # 'django.contrib.admin',

   # Uncomment the next line to enable admin documentation:

   # 'django.contrib.admindocs',

   'polls' <-- 요렇게 추가

)

- models.py 파일에 데이타 클래스를 정의

  Value Object을 정의하는데, Java와는 다르게, Data Type이나 객체간 relationship도 지정함

  

class Choice(models.Model):

    poll = models.ForeignKey(Poll) <-- Poll Class에 대한 FK

    choice = models.CharField(max_length=200) <-- varchar(200)

    votes = models.IntegerField() <-- Int type

    

- 마지막으로 model.py sql {appname} 해주면, 해당 DBMS에 테이블을 생성 SQL문을 만들어서 보여줌 (실제 실행은 안됨)

  테이블명은 {appname}_{modelclass명} 식으로 생성됨

  예를 들어 appname이 polls이고, VO가 위에 클래스 명처럼 Choice일 경우 테이블은 아래와 같은 형태로 생성됨

  CREATE TABLE "polls_choice" (

    "id" integer NOT NULL PRIMARY KEY,

    "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id"),

    "choice" varchar(200) NOT NULL,

    "votes" integer NOT NULL

  );

  테이블명과 Index등의 생성 규칙

The exact output will vary depending on the database you are using.

Table names are automatically generated by combining the name of the app (polls) and the lowercase name of the model -- poll and choice. (You can override this behavior.)

Primary keys (IDs) are added automatically. (You can override this, too.)

By convention, Django appends "_id" to the foreign key field name. (Yes, you can override this, as well.)

The foreign key relationship is made explicit by a REFERENCES statement.

It's tailored to the database you're using, so database-specific field types such as auto_increment (MySQL), serial (PostgreSQL), or integer primary key (SQLite) are handled for you automatically. Same goes for quoting of field names -- e.g., using double quotes or single quotes. The author of this tutorial runs PostgreSQL, so the example output is in PostgreSQL syntax.

The sql command doesn't actually run the SQL in your database - it just prints it to the screen so that you can see what SQL Django thinks is required. If you wanted to, you could copy and paste this SQL into your database prompt. However, as we will see shortly, Django provides an easier way of committing the SQL to the database.


- insert는 객체를 만든후에, object.save()를 하면됨

- select는 {ClassName}.objects.get({key}={value}) 를 하면 select x from ClassName where {key}={value} 와 같은 효과

  {ClassName}.objects.filter 하면 조건 검색

- 해당 object.delete() 하면 삭제


reference https://docs.djangoproject.com/en/1.4/intro/tutorial01/


그리드형