- 프로젝트 만들기
- 개발 서버
- 디비 설치
- 모델 만들기
- 모델 활성화 하기
- API 사용해서 동작시키기
장고 설치하기(mac)
sudo easy_install pip
sudo install django
프로젝트 만들기
django-admin.py startproject mysitemysite라는 프로젝트를 만든다.
mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py
기본 구조로
manage.py와 폴더 mysite를 가지고
mysite 폴더는 다시
__init__.py
settings.py
urls.py.
wsgi.py
를 가진 상태로 생성된다.
개발 서버
python manage.py runserver 를 커멘드에서 입력시
http://127.0.0.1:8000/ 주소에 개발용 서버가 실행 된다.
!파이썬 manage.py의의 runserver 0.0.0.0:8000
을 해서 외부 PC에서도 IP접근을 가능하게 할 수 있다.
DB 설정
DB 설정
프로젝트와 앱의 차이점
앱은 특정 기능을 세분화 시킨 것이라면 프로젝트는 각 앱들과 설정등을 모두 포함한 다수의 앱을 포함할 수 있는 것.
$ python manage.py startapp polls
polls 라는 앱을 만든다.
polls/ __init__.py admin.py models.py tests.py views.py
의 구조로 만들어진다.
polls 앱의 models.py 내에
from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
형태로 클래스를 만든다고 하자.
DB를 SQL문이 아닌 클래스 형태로 구현 할 수 있다.
여기서 Poll, Choice는 DB Viewer를 통해 확인하면
polls_choice , polls_poll이라는 형태로 테이블을 가지고
polls_choice는 id, poll_id,choice_text,votes라는 컬럼을,
polls_poll은 id,question, pub_date라는 컬럼을 가진다.
이처럼 클래스명은 테이블명, 변수는 컬럼이 된다.
모델 활성화하기
장고에서 가능한 것들로:
- DB구조 만들기(CREATE TABLE 문)
- 파이썬 DB 접근 API 를 Poll과 Choice 오브젝트를 이용해서 만들기
이전에 만든 polls 앱을 사용하려면
setting.py안에 있는 INSTALLED_APPS에 ‘polls’를 추가해준다.(안드로이드 manifest에 Activity를 추가하는 것과 유사한 개념이라고 생각 하면 될 것 같다.)
그리고 장고가 polls앱이 sql 문으로 어떻게 보이는지 확인하려면 커멘드에
python manage.py sql polls
라고 쳐준다.
python manage.py synced
을 해주면 테이블이 디비에서 갱신된다.
다시 한번 말한다면, Sql을 동작시켜서 sqlall을 통해 내 DB에 INSTALLED_APPS에 있지만, 내 DB에 존재하지 않는 것을 갱신 시켜주는 것이다.
API와 함께하기
python manage.py shell
쉘을 동작해서 한 줄씩 타이핑 해본다.
나중에는 문서로 동작 시키되 튜토리얼이니까 직접 해보자.
>>> from polls.models import Poll, Choice # Import the model classes we just wrote. # No polls are in the system yet. >>> Poll.objects.all() [] # Create a new Poll. # Support for time zones is enabled in the default settings file, so # Django expects a datetime with tzinfo for pub_date. Use timezone.now() # instead of datetime.datetime.now() and it will do the right thing. >>> from django.utils import timezone >>> p = Poll(question="What's new?", pub_date=timezone.now())
#p변수에 Poll클래스(값을 넣어서)을 만들고 저장한다.
# Save the object into the database. You have to call save() explicitly. >>> p.save() # Now it has an ID. Note that this might say "1L" instead of "1", depending # on which database you're using. That's no biggie; it just means your # database backend prefers to return integers as Python long integer # objects. >>> p.id 1 # Access database columns via Python attributes. >>> p.question "What's new?" >>> p.pub_date datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>) # Change values by changing the attributes, then calling save(). >>> p.question = "What's up?" >>> p.save() # objects.all() displays all the polls in the database. >>> Poll.objects.all() [<Poll: Poll object>]
Q) Poll 에 함수를 추가한다.(이 함수는 DB에는 원래 안나타는게 맞겠지?) DB는 데이터만 가지고 있을 뿐이니까?
->확인 결과 admin 사이트에서 볼 수 있지만 ,DB저장용은 아님.
import datetime from django.utils import timezone # ... class Poll(models.Model): # ... def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
함수 추가 후 다시 쉘로 돌아가서.
>>> from polls.models import Poll, Choice # Make sure our __unicode__() addition worked. >>> Poll.objects.all() [<Poll: What's up?>] # Django provides a rich database lookup API that's entirely driven by # keyword arguments. >>> Poll.objects.filter(id=1) [<Poll: What's up?>] >>> Poll.objects.filter(question__startswith='What') [<Poll: What's up?>] # Get the poll that was published this year. >>> from django.utils import timezone >>> current_year = timezone.now().year >>> Poll.objects.get(pub_date__year=current_year) <Poll: What's up?> # Request an ID that doesn't exist, this will raise an exception. >>> Poll.objects.get(id=2) Traceback (most recent call last): ... DoesNotExist: Poll matching query does not exist. # Lookup by a primary key is the most common case, so Django provides a # shortcut for primary-key exact lookups. # The following is identical to Poll.objects.get(id=1). >>> Poll.objects.get(pk=1) <Poll: What's up?> # Make sure our custom method worked. >>> p = Poll.objects.get(pk=1) >>> p.was_published_recently() True # Give the Poll a couple of Choices. The create call constructs a new # Choice object, does the INSERT statement, adds the choice to the set # of available choices and returns the new Choice object. Django creates # a set to hold the "other side" of a ForeignKey relation # (e.g. a poll's choices) which can be accessed via the API. >>> p = Poll.objects.get(pk=1) # Display any choices from the related object set -- none so far. >>> p.choice_set.all() [] # Create three choices. >>> p.choice_set.create(choice_text='Not much', votes=0) <Choice: Not much> >>> p.choice_set.create(choice_text='The sky', votes=0) <Choice: The sky> >>> c = p.choice_set.create(choice_text='Just hacking again', votes=0) # Choice objects have API access to their related Poll objects. >>> c.poll <Poll: What's up?> # And vice versa: Poll objects get access to Choice objects. >>> p.choice_set.all() [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] >>> p.choice_set.count() 3 # The API automatically follows relationships as far as you need. # Use double underscores to separate relationships. # This works as many levels deep as you want; there's no limit. # Find all Choices for any poll whose pub_date is in this year # (reusing the 'current_year' variable we created above). >>> Choice.objects.filter(poll__pub_date__year=current_year) [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] # Let's delete one of the choices. Use delete() for that. >>> c = p.choice_set.filter(choice_text__startswith='Just hacking') >>> c.delete()
'Program Language > dJango' 카테고리의 다른 글
nginx django 세팅하기 (0) | 2014.08.12 |
---|---|
django 3일간 튜토리얼 1~4까지 하고 의식의 흐름대로 정리 (0) | 2014.07.06 |
django 1.6 Tutorial04 한글 공부 (0) | 2014.07.06 |
django 1.6 Tutorial03 한글 공부 (0) | 2014.07.06 |
django 1.6 Tutorial02 한글 공부 (0) | 2014.07.06 |