使用restframework mongoengine如何创建一个queires?

时间:2016-12-09 06:41:42

标签: mongodb django-rest-framework mongoengine restframeworkmongoengine

models.py

User

Serializers.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)

views.py文件

from rest_framework import serializers
from rest_framework_mongoengine.serializers import DocumentSerializer

from models import Tool

class ToolSerializer(DocumentSerializer):

    class Meta:
        model = Tool

所以,我想创建像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仅为Pune区提供数据。

1 个答案:

答案 0 :(得分:1)

不幸的是,我自己还没有尝试过这个解决方案,但AFAIK,在纯数据库的DRF中使用Django-Filters package就可以了。

DRF-ME的类似物,称为drf-mongo-filters,由DRF-ME的合着者Maxim Vasiliev编写。它包含一组不错的测试,你可以用它来获得灵感。

基本上,你说的是:

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")

没有尝试对ViewSet做同样的事情,但是当他们从GenericView继承时,我猜他们也应该尊重filter_classfilter_backends参数。