3

模型.py

from mongoengine import Document,  fields

class Tool(Document):
    Fruit = fields.StringField(required=True)
    District = fields.StringField(required=True)
    Area = fields.StringField(required=True)
    Farmer = fields.StringField(required=True)

序列化程序.py 文件

from rest_framework import serializers
from rest_framework_mongoengine.serializers import DocumentSerializer

from models import Tool

class ToolSerializer(DocumentSerializer):

    class Meta:
        model = Tool

视图.py 文件

from django.template.response import TemplateResponse
from rest_framework_mongoengine.viewsets import ModelViewSet as MongoModelViewSet

from app.serializers import *

def index_view(request):
    context = {}
    return TemplateResponse(request, 'index.html', context)

class ToolViewSet(MongoModelViewSet):
    lookup_field = 'Fruit'
    serializer_class = ToolSerializer

    def get_queryset(self):
        return Tool.objects.all()

所以,我想创建查询,比如http://127.0.0.1:8000/api/tool/?Fruit=Banana只给我水果香蕉的所有数据。另外,http://127.0.0.1:8000/api/tool/?District=Pune只给我浦那区的数据。

4

1 回答 1

1

Unfortunately, I haven't tried this solution myself yet, but AFAIK, in pure DRF with SQL database you'd use Django-Filters package for this.

There's an analogue of it for DRF-ME, called drf-mongo-filters, written by Maxim Vasiliev, co-author of DRF-ME. It contains a decent set of tests, you could use for inspiration.

Basically, you say something like:

from rest_framework.test import APIRequestFactory
from rest_framework.generics import ListAPIView
from mongoengine import Document, fields

from drf_mongo_filters.filtersets import filters, Filterset, ModelFilterset
from drf_mongo_filters.backend import MongoFilterBackend

class TestFilter(Filterset):
    foo = filters.CharFilter()

class TestView(ListAPIView):
    filter_backends = (MongoFilterBackend,)
    filter_class = TestFilter
    serializer_class = mock.Mock()
    queryset = mock.Mock()

TestView.as_view()(APIRequestFactory().get("/?foo=Foo"))
TestView.queryset.filter.assert_called_once_with(foo="Foo")

Haven't tried doing the same with ViewSets, but as they inherit from GenericView, I guess, they should respect filter_class and filter_backends parameters, too.

于 2017-08-26T21:58:31.577 回答