django rest framework

4964 단어
DRF 설치
pip install djangorestframework
pip install markdown     #      
pip install django-filter  #      

DRF 구성
INSTALLED_APPS = (
    ...
    'rest_framework',  
    'django_filters',
)

DRF 베이스
#model.py
class GoodsCategory(models.Model):
    """
        
    """
    CATEGOTY_TYPE = (
        (1, '    '),
        (2, '    '),
        (3, '    '),
    )
    name = models.CharField(default='', max_length=30, verbose_name='   ', help_text='   ')
    code = models.CharField(default='', max_length=30, verbose_name='  code', help_text='  code')
    desc = models.TextField(default='', verbose_name='    ', help_text='    ')
    category_type = models.IntegerField(choices=CATEGOTY_TYPE, verbose_name='    ', help_text='    ')
    parent_category = models.ForeignKey("self", null=True, blank=True, verbose_name='     ', help_text='     ',
                                        related_name='sub_cat', on_delete=models.SET_NULL)
    is_tab = models.BooleanField(default=False, verbose_name='    ', help_text='    ')
    add_time = models.DateField(default=datetime.now, verbose_name='    ')

    class Meta:
        verbose_name = "    "
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name
#app.urls.py
from django.urls import path, include
from goods import views
from rest_framework.routers import DefaultRouter


router = DefaultRouter()
router.register('categorys', views.CategoryListViewSet)
router.register('', views.GoodsListViewSet)#       ,        

app_name = 'goods'

urlpatterns = [
    path('', include(router.urls)),
]
#serializer.py
from rest_framework import serializers

from goods import models

class GoodsCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = models.GoodsCategory
        fields = '__all__'
#view.py
from rest_framework import viewsets, mixins
from rest_framework import filters
from django_filters import rest_framework as r_filters

from goods.models import Goods
from goods import serializers



class GoodsListViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
         
    """
    #     
    queryset = Goods.objects.all()
    serializer_class = serializers.GoodsSerializer
    #    
    filter_backends = (filters.SearchFilter, r_filters.DjangoFilterBackend)
    filterset_class = GoodsFilter
    search_fields = ['name']
    #    
    pagination_class = GoodsPagination

필터
#filter.py
from django_filters import rest_framework as r_filters
from rest_framework import filters
from django.db.models import Q

class GoodsFilter(r_filters.FilterSet):
    """
       
    """
    min_price = r_filters.NumberFilter(field_name="shop_price", lookup_expr='gte', label='      ')
    max_price = r_filters.NumberFilter(field_name="shop_price", lookup_expr='lte', label='      ')
    top_category = r_filters.NumberFilter(method='top_category_filter')

    def top_category_filter(self, queryset, name, value):
        return queryset.filter(Q(category_id=value) | Q(category__parent_category_id=value) |
                               Q(category__parent_category__parent_category_id=value))

    class Meta:
        model = Goods
        fields = ['min_price', 'max_price']

DRF의 페이지 나누기 기능
전역 구성
#settings.py     
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 10
}
#response style
HTTP 200 OK
{
    "count": 1023
    "next": "https://api.example.org/accounts/?page=5",
    "previous": "https://api.example.org/accounts/?page=3",
    "results": [
       …
    ]
}

부분적 구성
class GoodsPagination(PageNumberPagination):
    """
           
    """
    page_size = 10
    max_page_size = 100
    page_size_query_param = 'page_size'


class CategoryListViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
           
    """
    queryset = GoodsCategory.objects.filter(category_type=1)
    serializer_class = serializers.GoodsCategorySerializer


class CategoryListPaginationViewSet(CategoryListViewSet, GoodsPagination):
    """
                  
    """
    pagination_class = GoodsPagination

좋은 웹페이지 즐겨찾기