Django-rest-framework多條件查詢/分頁/多表Json

Django-rest-framework多條件查詢/分頁/多表Json

django-rest-framework多條件查詢需要覆寫ListAPIView.get_queryset方法,代碼示例:

def get_queryset(self):
    """
    使用request.query_params實現多條件查詢,也可以使用django filter ,較簡單的
    方法是在filter_fields中指定要過濾的字段,但只能表示等值,不靈活,靈活的方式是
    使用FilterSet,如下示例:
    class ProductFilter(django_filters.rest_framework.FilterSet):
        min_price = django_filters.NumberFilter(name="price", lookup_expr='gte')
        max_price = django_filters.NumberFilter(name="price", lookup_expr='lte')
        class Meta:
            model = Product
            fields = ['category', 'in_stock', 'min_price', 'max_price']

    class ProductList(generics.ListAPIView):
        queryset = Product.objects.all()
        serializer_class = ProductSerializer
        filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)
        filter_class = ProductFilter

    """
    queryset = Snippet.objects.all()
    title = self.request.query_params.get('title', None)
    language = self.request.query_params.get('language', None)
    style = self.request.query_params.get('style', None)

    aQ = Q()
    if title is not None:
        aQ.add(Q(title__startswith=title), Q.AND)
    if language is not None:
        aQ.add(Q(language=language), Q.AND)
    if style is not None:
        aQ.add(Q(style=style), Q.AND)

    queryset = queryset.filter(aQ).order_by("-id")

    return queryset


至於分頁,只需要在View中指定分頁類,或者在settings.py中指定

pagination_class = StandardResultsSetPagination
#或setting.py
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 100}


涉及到多表的Json,重新編寫Serializer,附加上所需要的字段,在View中使用新的Serializer。

'''
關於Serializer,一般情況下,一個實體(Model)對應一個Serializer;
在涉及到表關聯查詢顯示時,可以額外編寫Serializer,包含關聯表中
所需要的字段。
'''
class SnippetJoinUserSerializer(ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    email = serializers.ReadOnlyField(source='owner.email')
    user_id = serializers.ReadOnlyField(source='owner.id')
    last_login = serializers.ReadOnlyField(source='owner.last_login')

    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style', 'owner',
                  'email','user_id','last_login')

輸出結果就是包含了user信息的Json。

GET /snippet_join_users/
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "count": 8,
    "next": "http://127.0.0.1:8000/snippet_join_users/?page=2",
    "previous": null,
    "results": [
        {
            "id": 8,
            "title": "test8",
            "code": "test",
            "linenos": false,
            "language": "abap",
            "style": "algol",
            "owner": "admin",
            "email": "[email protected]",
            "user_id": 1,
            "last_login": "2016-12-11T03:50:40.909685Z"
        },
        {
            "id": 7,
            "title": "test7",
            "code": "test",
            "linenos": false,
            "language": "abap",
            "style": "algol",
            "owner": "admin",
            "email": "[email protected]",
            "user_id": 1,
            "last_login": "2016-12-11T03:50:40.909685Z"
        },
        {
            "id": 6,
            "title": "test6",
            "code": "test",
            "linenos": false,
            "language": "abap",
            "style": "algol",
            "owner": "admin",
            "email": "[email protected]",
            "user_id": 1,
            "last_login": "2016-12-11T03:50:40.909685Z"
        },
        {
            "id": 5,
            "title": "test5",
            "code": "test",
            "linenos": false,
            "language": "abap",
            "style": "algol",
            "owner": "admin",
            "email": "[email protected]",
            "user_id": 1,
            "last_login": "2016-12-11T03:50:40.909685Z"
        },
        {
            "id": 4,
            "title": "test4",
            "code": "test",
            "linenos": false,
            "language": "abap",
            "style": "algol",
            "owner": "admin",
            "email": "[email protected]",
            "user_id": 1,
            "last_login": "2016-12-11T03:50:40.909685Z"
        }
    ]
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章