바뀜

둘러보기로 가기 검색하러 가기
676 바이트 추가됨 ,  2021년 5월 26일 (수) 08:34
4번째 줄: 4번째 줄:  
=데이터 다루기=
 
=데이터 다루기=
 
==데이터 불러오기==
 
==데이터 불러오기==
===모델의 pk 얻기===
+
===객체 다 가져오기===
 +
만들어진 모든 객체를 다 불러온다.<syntaxhighlight lang="python">
 +
from django.shortcuts import render
 +
from .models import 모델명  # 모델을 임포트 한다.
 +
 
 +
# 모델.objects는 객체목록을 받는다는 의미이다.
 +
def index(request):
 +
    목록 = 모델.objects.all()
 +
</syntaxhighlight>모델.objects.all[:5] 처럼 상위 5개만 가져오는 방식도 가능.
 +
 
 +
=== 모델의 pk 얻기 ===
 
모델명.id 가 pk이다.
 
모델명.id 가 pk이다.
===객체 조회===
+
===특정 객체 불러오기===
 
pk를 알면 다음과 같이 해당 객체를 불러올 수 있다. <code>모델.objects.get(id=pk)</code><syntaxhighlight lang="python">
 
pk를 알면 다음과 같이 해당 객체를 불러올 수 있다. <code>모델.objects.get(id=pk)</code><syntaxhighlight lang="python">
from django.shortcuts import get_object_or_404#기본키값에 해당하는 모델이 없을 경우 404 에러 반환.
+
from django.shortcuts import get_object_or_404 # 기본키값에 해당하는 모델이 없을 경우 404 에러 반환.
from .models import 모델명#모델을 임포트 한다.
+
from .models import 모델명 # 모델을 임포트 한다.
   −
객체 = 모델.objects.get(pk=기본키값) #없으면 에러가 나는데, 서버에러로 인식한다.
+
객체 = 모델.objects.get(pk=기본키값) # 없으면 에러가 나는데, 서버에러로 인식한다.
객체 = 모델.objects.get(id=기본키값) #위와 동일
+
객체 = 모델.objects.get(id=기본키값) # 위와 동일
객체 = 모델.objects.filter(id=기본키값) #위와 동일
+
객체 = 모델.objects.filter(id=기본키값) # 위와 동일
객체 = get_object_or_404(모델명, pk=기본키값) #서버에러가 나지 않게끔.
+
객체 = get_object_or_404(모델명, pk=기본키값) # 서버에러가 나지 않게끔 404 에러를 발생시킨다.
       
</syntaxhighlight>
 
</syntaxhighlight>
===목록 조회===
  −
<syntaxhighlight lang="python">
  −
from django.shortcuts import render
  −
from .models import 모델명#모델을 임포트 한다.
  −
  −
#모델.objects는 객체목록을 받는다는 의미이다.
  −
def index(request):
  −
    목록 = 모델.objects.order_by('-create_date') #create_date속성의 역순으로 정리하라는 의미.
  −
    context={'템플릿에서 쓸 변수명':목록)
  −
    return render(request, '템플릿', context)
  −
</syntaxhighlight>order_by('?') 로 두면 객체들을 랜덤하게 배치한다.
  −
===객체 다 가져오기===
  −
<syntaxhighlight lang="python">
  −
from django.shortcuts import render
  −
from .models import 모델명#모델을 임포트 한다.
  −
  −
#모델.objects는 객체목록을 받는다는 의미이다.
  −
def index(request):
  −
    목록 = 모델.objects.all
  −
</syntaxhighlight>모델.objects.all[:5] 처럼 상위 5개만 가져오는 방식도 가능.
   
==필터 사용==
 
==필터 사용==
 
===필터로 걸러서 가져오기===
 
===필터로 걸러서 가져오기===
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
 
from django.shortcuts import render
 
from django.shortcuts import render
from .models import 모델명#모델을 임포트 한다.
+
from .models import 모델명 # 모델을 임포트 한다.
   −
#모델.objects는 객체목록을 받는다는 의미이다.
+
# 모델.objects는 객체목록을 받는다는 의미이다.
 
def index(request):
 
def index(request):
 
     목록 = 모델.objects.filter(칼럼명 = True, >0 따위의 조건들...)
 
     목록 = 모델.objects.filter(칼럼명 = True, >0 따위의 조건들...)
     목록2= 목록.objects.filter(조건들..)#객체에 또다시 필터를 걸 수도 있다.
+
     목록2= 목록.objects.filter(조건들..) # 걸러진 객체들에 또다시 필터를 걸 수도 있다.
 
</syntaxhighlight>필터는 몇번이라도 걸 수 있는데, 장고는 지연평가 방식을 사용하기 때문에 실제로 데이터를 질의하는 것은 한 번 뿐이다. 덕분에 부하가 걸리지 않고도 filter를 자유롭게 사용할 수 있다.<syntaxhighlight lang="python">
 
</syntaxhighlight>필터는 몇번이라도 걸 수 있는데, 장고는 지연평가 방식을 사용하기 때문에 실제로 데이터를 질의하는 것은 한 번 뿐이다. 덕분에 부하가 걸리지 않고도 filter를 자유롭게 사용할 수 있다.<syntaxhighlight lang="python">
 
def index(request):
 
def index(request):
60번째 줄: 50번째 줄:  
필터 안에서 > 따위의 기호는 사용할 수 없다. 대신 __을 사용해 명령을 지정한다.
 
필터 안에서 > 따위의 기호는 사용할 수 없다. 대신 __을 사용해 명령을 지정한다.
 
{| class="wikitable"
 
{| class="wikitable"
|+
   
!기능
 
!기능
 
!설명
 
!설명
82번째 줄: 71번째 줄:  
question_list = question_list.filter(created_date__range=(first_date, last_date))
 
question_list = question_list.filter(created_date__range=(first_date, last_date))
   −
</syntaxhighlight>
+
</syntaxhighlight>이외 다양한 연산자를 사용할 수 있다.
 +
 
 
===날짜데이터===
 
===날짜데이터===
 
필터에 들어가는 날짜데이터는 datetime.date 형태의 데이터여야 한다. 다음과 같은 형태로 쓴다.<syntaxhighlight lang="python">
 
필터에 들어가는 날짜데이터는 datetime.date 형태의 데이터여야 한다. 다음과 같은 형태로 쓴다.<syntaxhighlight lang="python">
96번째 줄: 86번째 줄:  
def index(request):
 
def index(request):
 
     목록 = 모델.objects.exclude(칼럼명 = True, >0 따위의 조건들...)
 
     목록 = 모델.objects.exclude(칼럼명 = True, >0 따위의 조건들...)
</syntaxhighlight>
  −
===삭제하기===
  −
해당 객체를 불러온 후 delete()를 붙여준다.<syntaxhighlight lang="python">
  −
def index(request):
  −
    목록 = 모델.objects.exclude(칼럼명 = True, >0 따위의 조건들...).delete() #조건을 제외한 것들을 삭제한다.
   
</syntaxhighlight>
 
</syntaxhighlight>
 
===특정단어 검색===
 
===특정단어 검색===
 
속성에 특정 단어가 포함된 객체를 불러올 땐 다음과 같이 한다. <code>모델.objects.filter(속성__contains='장고')</code> (언더바가 2개임에 유의)
 
속성에 특정 단어가 포함된 객체를 불러올 땐 다음과 같이 한다. <code>모델.objects.filter(속성__contains='장고')</code> (언더바가 2개임에 유의)
===객체의 속성에 접근===
  −
모델.속성 형태로 속성에 접근 가능하다. 일반적으로
  −
  −
<code>객체 = 모델.objects.get(id=pk)</code>
     −
객체.속성 형태로 접근한다.(수정을 하고 반드시 저장을 해주어야 한다.)
   
===외래키 연결===
 
===외래키 연결===
 
모델에서 외래키로 1:N 연결을 한 경우.
 
모델에서 외래키로 1:N 연결을 한 경우.
153번째 줄: 133번째 줄:  
때문에 annotate를 사용해 새로운 속성을 만들어준 후에 oreder_by를 써야 한다. <code>모델.objects.annotate(num=Count('하위모델')).order_by('-num', '-create_date')</code> # -num으로 우선배치한 후, 같은 숫자가 나온다면 만들어진 순서로 우열을 정한다.)
 
때문에 annotate를 사용해 새로운 속성을 만들어준 후에 oreder_by를 써야 한다. <code>모델.objects.annotate(num=Count('하위모델')).order_by('-num', '-create_date')</code> # -num으로 우선배치한 후, 같은 숫자가 나온다면 만들어진 순서로 우열을 정한다.)
   −
Count를 사용하기 위해선 <code>from django.db.models import Count</code> 가 필요하다.  
+
Count를 사용하기 위해선 <code>from django.db.models import Count</code> 가 필요하다.  
 +
 
 +
== 데이터 조작하기 ==
 +
 
 +
===객체 정렬===
 +
<syntaxhighlight lang="python">
 +
from django.shortcuts import render
 +
from .models import 모델명#모델을 임포트 한다.
 +
 
 +
#모델.objects는 객체목록을 받는다는 의미이다.
 +
def index(request):
 +
    목록 = 모델.objects.order_by('-create_date') #create_date속성의 역순으로 정리하라는 의미.
 +
    context={'템플릿에서 쓸 변수명':목록)
 +
    return render(request, '템플릿', context)
 +
</syntaxhighlight>order_by('?') 로 두면 객체들을 랜덤하게 배치한다.
 +
 
 +
===객체의 속성에 접근===
 +
모델.속성 형태로 속성에 접근 가능하다. 일반적으로
 +
 
 +
<code>객체 = 모델.objects.get(id=pk)</code>
 +
 
 +
객체.속성 형태로 접근한다.(수정을 하고 반드시 저장을 해주어야 한다.)
 +
 
 +
=== 데이터 생성하기 ===
 +
<syntaxhighlight lang="python">
 +
def index(request):
 +
    c = 모델.objects.create(칼럼="내용", 칼럼2="내용2")
 +
</syntaxhighlight>
 +
 
 +
=== 데이터 수정하기 ===
 +
<syntaxhighlight lang="python">
 +
def index(request):
 +
    c.수정할칼럼 = "수정할 내용"
 +
    c.save()  # 항상 저장을 해주어야 한다.
 +
</syntaxhighlight>
 +
 
 +
=== 데이터 삭제하기 ===
 +
조회, 조작한 후 <code>모델.delete()</code>를 실행.
 +
 
 +
 
 +
해당 객체를 불러온 후 delete()를 붙여준다.<syntaxhighlight lang="python">
 +
def index(request):
 +
    c.delete()
 +
</syntaxhighlight>여러 개를 동시에 삭제하고 싶은 경우 filter, exclude 등을 사용하여 조건에 맞는 것들을 선택한 후 통째로 삭제할 수 있다.<syntaxhighlight lang="python">
 +
def index(request):
 +
    목록 = 모델.objects.exclude(칼럼명 = True, >0 따위의 조건들...).delete()  # 조건을 제외한 것들을 삭제한다.
 +
</syntaxhighlight>
 +
 
 
==유의==
 
==유의==
 
탬플릿에선 위 속성들을 그대로 사용할 수 있지만, 괄호는 빼주고 기입한다.
 
탬플릿에선 위 속성들을 그대로 사용할 수 있지만, 괄호는 빼주고 기입한다.
==데이터 저장하기==
  −
===객체 저장===
  −
객체(모델)를 조회, 조작한 후 모델<code>.save()</code>를 실행한다.
  −
==데이터 삭제==
  −
===객체 삭제===
  −
조회, 조작한 후 <code>모델.delete()</code>를 실행.
   
[[분류:장고 뷰]]
 
[[분류:장고 뷰]]

둘러보기 메뉴