Django

파이썬 장고 실무 심화 2주차 2_serializer, GET, POST

끈끈 2023. 4. 19. 16:44

 

serializer를 사용하면 json 형태의 string으로 만들어 줌

 

GET

 

articles > serializers.py:

from rest_framework import serializers
from articles.models import Article


class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = "__all__" # 모든 필드를 가져오겠다

 

articles > views.py:

from rest_framework.response import Response
from rest_framework.decorators import api_view
from articles.models import Article
from articles.serializers import ArticleSerializer


@api_view(['GET'])
def index(request):
    articles = Article.objects.all()
    article = articles[0]
    serializer = ArticleSerializer(article)
    return Response(serializer)

 

You passed a Serializer instance as data, but probably meant to pass serialized `.data` or `.error`. representation.

 

AssertionError

 

return Response(serializer.data) # .data 추가

 

 

데이터가 여러 개일 경우

 

@api_view(['GET'])
def index(request):
    articles = Article.objects.all()
    serializer = ArticleSerializer(articles)
    return Response(serializer.data)

 

Got AttributeError when attempting to get a value for field `title` on serializer `ArticleSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'title'.

 

AttributeError

 

@api_view(['GET'])
def index(request):
    articles = Article.objects.all()
    serializer = ArticleSerializer(articles, many=True) # many=True 추가
    return Response(serializer.data)

 

 


 

POST

 

articles > views.py:

from rest_framework.response import Response
from rest_framework.decorators import api_view
from articles.models import Article
from articles.serializers import ArticleSerializer


@api_view(['GET', 'POST'])
def index(request):
    if request.method == 'GET':
        articles = Article.objects.all()
        serializer = ArticleSerializer(articles, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = ArticleSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            print(serializer.errors)
            return Response(serializer.errors)  # 프론트에서 에러 표시는 좋지 않다

 

serializer.errors

 

articles > models.py:

content = models.TextField(null=True, blank=True)

 

db.sqlite3

 


 

HTTP 200 OK

 

articles > views.py:

from rest_framework import status #####
from rest_framework.response import Response
from rest_framework.decorators import api_view
from articles.models import Article
from articles.serializers import ArticleSerializer


@api_view(['GET', 'POST'])
def index(request):
    if request.method == 'GET':
        articles = Article.objects.all()
        serializer = ArticleSerializer(articles, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = ArticleSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED) #####
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) #####

 

HTTP 201 Created

 

https://www.django-rest-framework.org/api-guide/status-codes/

 

Status codes - Django REST framework

 

www.django-rest-framework.org