Filtering 은 Request 걸러보내기, Search는 Response 걸러받기
models.py
from django.db import models
from django.conf import settings
# Create your models here.
class UserPost(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
author = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE)
Filtering
views.py
from .models import UserPost
from .serializer import UserPostSerializer
from rest_framework import viewsets
class UserPostViewSet(viewsets.ModelViewSet):
queryset = UserPost.objects.all()
serializer_class = UserPostSerializer
def get_queryset(self):
# 내부에서 쿼리셋을 작성
qs = super().get_queryset()
# qs = qs.filter(author_id = 1) # .filter 또는 .exclude
# 지금 만약 로그인이 되어있다면, 로그인한 유저의 글만 필터링
if self.request.user.is_authenticated:
qs = qs.filter(author=self.request.user)
# 만약 로그인이 되어있지 않다면, 비어있는 쿼리셋을 리턴
else:
qs = qs.none()
return qs
Search
views.py
from .models import UserPost
from .serializer import UserPostSerializer
from rest_framework import viewsets
from rest_framework.filters import SearchFilter
class UserPostViewSet(viewsets.ModelViewSet):
queryset = UserPost.objects.all()
serializer_class = UserPostSerializer
filter_backends = [SearchFilter]
search_fields = ('title',)
# 어떤 컬럼을 기반으로 search를 할 건지 지정 -> 튜플
'Server > django' 카테고리의 다른 글
[Django] Authentication & Permission (0) | 2020.05.29 |
---|---|
[Django] Pagination (0) | 2020.05.25 |
[Django] View of DRF ( Django Rest Framework ) (0) | 2020.05.04 |
[Django] JSON 직렬화 - Serializer (0) | 2020.04.28 |
[Django] REST Architecture (0) | 2020.04.28 |