django rest framework
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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.