https://www.json.org/json-en.html
articles > admin.py:
from django.contrib import admin
from articles.models import Article # articles 앱의 Article 모델
admin.site.register(Article)
articles > models.py:
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self): # 모델 클래스 객체의 문자열 표현을 리턴
return str(self.title)
drf_week2 > urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('articles/', include("articles.urls")),
]
articles > urls.py:
from django.urls import path
from articles import views
urlpatterns = [
path('index/', views.index, name="index"),
]
articles > views.py:
from rest_framework.response import Response
def index(request):
return Response("연결 완료!")
https://www.django-rest-framework.org/tutorial/2-requests-and-responses/
.accepted_renderer not set on Response
>>> you forgot to add the @api_view and the @renderer_classes decorator to your view.
articles > views.py:
from rest_framework.response import Response
from rest_framework.decorators import api_view
@api_view(['GET'])
def index(request):
return Response("연결 완료!")
api_view란? rest_framework에서 API를 간편하게 사용하게 하기 위한 브라우저블 API로
직접 브라우저에서 조작이 가능하게 해주고
돌려주는 response 또한 있는데 rest_framework.response
db의 articles의 데이터 가져오기
articles > views.py:
from rest_framework.response import Response
from rest_framework.decorators import api_view
from articles.models import Article
@api_view(['GET'])
def index(request):
articles = Article.objects.all()
print(articles) # <QuerySet [<Article: hi>]>
return Response(articles)
Object of type Article is not JSON serializable
>>> Response에 담을 수 있는 값은 string, dictionary, list
def index(request):
articles = Article.objects.all()
article = articles[0]
article_data = {
'title': article.title,
'content': article.content,
'created_at': article.created_at,
'updated_at': article.updated_at,
}
return Response(article_data)
NEXT : Serializer
'Django' 카테고리의 다른 글
파이썬 장고 실무 심화 2주차 3_PUT, DELETE (0) | 2023.04.19 |
---|---|
파이썬 장고 실무 심화 2주차 2_serializer, GET, POST (3) | 2023.04.19 |
DRF 시작하기 (0) | 2023.04.19 |
파이썬 장고 실무 심화 1주차_DRF, HTTP (10) | 2023.04.18 |
HTTP response status codes 상태 코드 (0) | 2023.04.18 |