본문 바로가기
카테고리 없음

Web 개발 :: Django 머신러닝 프로젝트 Code Review _ User_TIL#38

by 올커 2022. 10. 26.

■ JITHub 개발일지 38일차

□  TIL(Today I Learned) ::

Django 머신러닝 프로젝트 Code Review _ Post, DRF

   1) 해결 및 알게된 점

(1) DRF에서 ArticleView를 작성할 때 아래와 같이 클래스뷰로도 작성할 수 있다.

from django.shortcuts import render

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView


# 기존 함수 방식
@api_view(['GET', 'POST'])
def index(request):
    if request.method == 'GET':
        print("get!")
        return Response({'message':'get success!'})
    
    if request.method == 'POST':
        print('post!')
        return Response({'message':'post success!'})


# 클래스뷰로 변환 방식
class ArticleView(APIView):
    def get(self, request):
        print("get!")
        return Response({'message':'get success!'})
    
    def post(self, request):
        print('post!')
        return Response({'message':'post success!'})

 

 (2) filter나 all을 사용했을 경우 결과가 있건 없건 쿼리셋으로 출력된다. 데이터로 사용하기 위해서는 해당 변수의 뒤에 .data를 붙여준다.

 

 (3) 아래의 코드에서는 오류가 발생할 경우 is_valid에서 로직이 끝나고, 발생하지 않을 경우 save까지 진행된다.

class ArticleView(APIView):
    def get(self, request):
        all_articles = Article.objects.all()
        return Response(ArticleSerializer(all_articles, many=True).data)
    
    def post(self, request):
        article = ArticleSerializer(data=request.data)
        # 검증
        article.is_valid(raise_exception=True)
        # 생성
        article.save()

        return Response(article.data)

 (4) get_object_or_404 와 get_list_or_404 차이
    - get_object_or_404(Post, id=id) = Post.objects.get(id=id)
    - get_list_or_404(Postm id=id) = Post.object.filter(id=id)

 

 (5) 게시글이나 댓글을 최근 순으로 정렬하고 싶을 때, 아래 4번째 줄처럼 .order_by('-created_at')을 사용할 수 있지만 다른 방법이 있다.

def index(request):
    context = dict()
    context['users'] = User.objects.all()
    context['posts'] = Post.objects.all().order_by('-created_at')
    return render(request, 'post/post/index.html', context=context)

 - models.py에서 해당 모델에 class Meta를 만들어주고  아래와 같이 작성하여 추가해주면 view에서는 별도 옵션을 주지 않아도 된다.

class Meta:
	ording['-create_at']

 (6) 게시글 생성하는 방법(save or create)

# save를 사용할 경우
...
elif request.method =='POST':
    post = Post()
    post.title = request.POST.get('title')
    post.content = request.POST.get('content')
    post.author = request.user
    post.save()
    return redirect('post:post-detail',post_id=post.id)


# create를 사용할 경우
...
elif request.method =='POST':
    title = request.Post.get('title')
    content = request.Post.get('content')
    author = request.user
    post.objects.create(title=title, content=content, author=author)

 

반응형

댓글