.filter(), .exclude(), .order_by() 등 파이썬다운 메서드를 사용하여 원하는 데이터를 손쉽게 생성, 조회, 수정, 삭제할 수 있다.
Django → DB : Django(QuerySet API)에서 ORM을 통해 데이터베이스로 정보를 요청할 때DB → Django : 데이터베이스가 요청에 대한 응답을 보낼 때,
Article (모델 클래스).objects (매니저, manager).all(), .filter() 등의 쿼리 메서드를 호출.all() (QuerySet API 메서드)pip install ipython
pip freeze > requirements.txtpython manage.py shell대부분의 소프트웨어가 가지는 기본적인 데이터 처리 기능인 생성(Create), 조회(Read), 수정(Upadate), 삭제(Delete)를 묶어 이르는 말
빈 객체 생성 후 값 할당 및 저장
article = Article()
article.title = 'first'
article.content = 'django!'
article.save()
초기 값과 함께 객체 생성 및 저장
article = Article(title='second', content='django!')
article.save()
create() 메서드로 한 번에 생성 및 저장
Article.objects.create(title='third', content='django!')
all() : 전체 데이터 조회filter() : 주어진 매개변수와 일치하는 객체를 포함하는 QuerySet 반환get() : 주어진 매개변수와 일치하는 객체를 반환 (Only one)
filter(): QuerySet으로 반환 → iterableget(): 인스턴스로 반환# 수정할 인스턴스 조회 (주로 1개씩 수정 → get() 사용)
article = Article.objects.get(pk=1)
# 인스턴스 변수를 변경
article.title = 'byebye'
# 저장
article.save()# 삭제할 인스턴스 조회
article = Article.objects.get(pk=1)
# delete 메서드 호출
article.delete()
# 삭제한 데이터는 더이상 조회할 수 없음
Article.objects.get(pk=1) # DoesNotExist: Article matching query does not exist.from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('articles/', include('articles.urls')),
]from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]from .models import Article
def index(request):
articles = Article.objects.all()
context = {
'articles': articles,
}
return render(request, 'articles/index.html', context)<h1>Articles</h1>
<hr>
{% for article in articles %}
<div>
<p>글 번호: {{ article.pk }}</p>
<p>글 제목: {{ article.title }}</p>
<p>글 내용: {{ article.content }}</p>
</div>
<hr>
{% endfor %}from django.urls import path
from . import views
urlpatterns = [
...,
path('<int:pk>/' views.detail, name='detail'),
]from .models import Article
def detail(request, pk):
article = Article.objects.get(pk=pk)
context = {
'article': article,
}
return render(request, 'articles/detail.html', context)<h2>Detail</h2>
<h3>{{ article.pk }} 번째 글</h3>
<hr>
<p>제목: {{ article.title }}</p>
<p>내용: {{ article.content }}</p>
<p>작성일: {{ article.created_at }}</p>
<p>수정일: {{ article.updated_at }}</p>
<hr>
<a href="{% url 'articles:index' %}">[back]</a>{% for article in articles %}
<div>
<p>글 번호: {{ article.pk }}</p>
<p>
글 제목: <a href="{% url "articles:detail" article.pk %}">{{ article.title }}</a>
</p>
<p>글 내용: {{ article.content }}</p>
</div>
<hr>
{% endfor %}urlpatterns = [
...,
path('new/', views.new, name='new'),
]def new(request):
return render(request, 'articles/new.html')<h1>NEW</h1>
<form action="#" method="POST">
<div>
<label for="title">Title: </label>
<input type="text" name="title" id="title">
</div>
<div>
<label for="context">Content: </label>
<textarea name="content" id="content"></textarea>
</div>
<input type="submit">
</form>
<hr>
<a href="{% url 'articles:index' %}">[back]</a><h1>Articles</h1>
<a href="{% url 'articles:new' %}">NEW</a>
<hr>
...urlpatterns = [
...,
path('create/', views.create, name='create'),
]def create(request):
title = request.POST.get('title')
content = request.POST.get('content')
article = Article(title=title, content=content)
article.save()
return render(request, 'articles/create.html')<h1>게시글이 작성되었습니다.</h1><h1>NEW</h1>
<form action="{% url 'articles:create' %}" method="POST">
<div>
<label for="title">Title: </label>
<input type="text" name="title" id="title">
</div>
<div>
<label for="context">Content: </label>
<textarea name="content" id="content"></textarea>
</div>
<input type="submit">
</form>
<hr>
<a href="{% url 'articles:index' %}">[back]</a>C → POST
R → GET
U → POST
D → POST<h1>NEW</h1>
<form action="{% url 'articles:create' %}" method="POST">
{% csrf_token %}redirect() : 클라이언트가 인자에 작성된 주소로 다시 요청을 보내도록 하는 함수def create(request):
title = request.POST.get('title')
content = request.POST.get('content')
article = Article(title=title, content=content)
article.save()
return redirect('articles:detail', article.pk)from django.urls import path
from . import views
urlpatterns = [
...,
path('<int:pk>/delete' views.delete, name='delete'),
]def delete(request, pk):
article = Article.objects.get(pk=pk)
article.delete()
return redirect('articles:index')<h2>Detail</h2>
...
<hr>
<form action="{% url 'articles:delete' article.pk %}" method="POST">
{% csrf_token %}
<input type="submit" value="DELETE">
</form>
<a href="{% url 'articles:index' %}">[back]</a>urlpatterns = [
...,
path('<int:pk>/edit/', views.edit, name='edit'),
]def edit(request, pk):
article = Article.objects.get(pk=pk)
context = {
'article': article,,
}
return render(request, 'articles/edit.html', context)<h1>EDIT</h1>
<form action="#" method="POST">
{% csrf_token %}
<div>
<label for="title">Title: </label>
<input type="text" name="title" id="title" value="{{ article.title }}">
</div>
<div>
<label for="context">Content: </label>
<textarea name="content" id="content">{{ article.content }}</textarea>
</div>
<input type="submit">
</form>
<hr>
<a href="{% url 'articles:index' %}">[back]</a>...
<a href="{% url 'articles:edit' article.pk %}">EDIT</a><br>
<form action="{% url 'articles:delete' article.pk %}" method="POST">
{% csrf_token %}
<input type="submit" value="DELETE">
</form>
<a href="{% url 'articles:index' %}">[back]</a>urlpatterns = [
...,
path('<int:pk>/update/', views.update, name='update'),
]def update(request, pk):
article = Article.objects.get(pk=pk)
article.title = request.POST.get('title')
article.content = request.POST.get('content')
article.save()
return redirect('articles:detail', article.pk)<h1>EDIT</h1>
<form action="{% url 'articles:update' article.pk %}" method="POST">
{% csrf_token %}
<div>
<label for="title">Title: </label>
<input type="text" name="title" id="title" value="{{ article.title }}">
</div>
<div>
<label for="context">Content: </label>
<textarea name="content" id="content">{{ article.content }}</textarea>
</div>
<input type="submit">
</form>
<hr>
<a href="{% url 'articles:index' %}">[back]</a>