코딩일지/TIL: Today I Learned

20221028 TIL

야언 2022. 10. 28. 19:12

오늘의 배운 것

  • 장고 심화 - 1~5주차 복습
  • drf 타임어택

 

 

DRF 타임어택 테스트

urls.py

from django.contrib import admin
from django.urls import path, include
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

urlpatterns = [
    path("admin/", admin.site.urls),
    path('api/token/', TokenObtainPairView.as_view()),
    path('api/token/refresh/', TokenRefreshView.as_view()),
    path("api/article/", include("article.urls")),
]

article - urls.py

from django.urls import path
from article import views


urlpatterns = [
    path('', views.ArticleView.as_view(), name='article_view'),

]

 

 

 

article - models.py

from tkinter import CASCADE
from django.db import models
# from django.contrib.auth.models import User  # 1번
from django.contrib.auth import get_user_model  # 2번

class Article(models.Model):
    author = models.ForeignKey(get_user_model(), verbose_name="작성자", on_delete=models.CASCADE)
    title = models.CharField(max_length=50)
    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)

article - serializers.py

from rest_framework import serializers
from article.models import Article

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = "__all__"

 

article - views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from article.models import Article
from article.serializers import ArticleCreateSerializer, ArticleSerializer

class ArticleView(APIView):
    def get(self, reuqest):
        articles = Article.objects.all()
        serializer = ArticleSerializer(articles, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)
    
    
    def post(self, request):
        serializer = ArticleCreateSerializer(data=request.data)
        # 방법 1 
        # if serializer.is_valid():
        #     serializer.save(author=request.user)
        #     return Response(serializer.data, status=status.HTTP_201_CREATED)
        # else:
        #     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        
        # 방법 2
        serializer.is_valid(raise_exception=True)
        serializer.save(author=request.user)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

 

 

여기까진 모두 배운대로였는데 author 모델을 장고 내에 있는 user모델을 foreign키로 가져와 쓰다보니 post부분에 애로사항이 꽃피었다. 하필이면 제대로 이해 못했던 부분인 serializer의 필드부분 문제.. author가 제대로 불러와지지 않는듯한 문제로 is_valid()함수부분에서 걸려서 에러가 난 것 같다.

타임어택 중에는Article model의 author 이름을 user로 바꿔서 해결

 

정답

article - serializers.py

# 방법 1        
class ArticleCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ("id", "title", "content")

# 방법2
class ArticleCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = '__all__'
        
        extra_kwargs = {
            'author' : {'read_only': True}
        }
        
# 방법3
class ArticleCreateSerializer(serializers.ModelSerializer):
    author = serializers.SerializerMethodField()
    
    class Meta:
        model = Article
        fields = '__all__'
        
        extra_kwargs = {
            'author': {'read_only': True}
        }
    
    def create(self, validated_data):
        author = self.context["request"].user

 

author 부분을 read_only 속성을 부여해서  처리할 수 있었다