赞
踩
1. pip install rest_framework_mongoengine
2. 新建一个Django项目
3. 在setting.py中配置
4. 新建数据库模型
- import mongoengine
-
- # Create your models here.
- STATUS = ((0, '启用'), (1, '废弃'))
-
- class Company(mongoengine.Document):
- name = mongoengine.StringField(max_length=100, required=True)
- fullname = mongoengine.StringField(max_length=250, required=True)
- address = mongoengine.StringField(max_length=250)
- status = mongoengine.IntField(default=0, choices=STATUS, required=False)
- date = mongoengine.DateTimeField()
- meta = {'collection': 'company'}
- def __unicode__(self):
- return self.name
5. 序列化
- from rest_framework_mongoengine import serializers
- class CompanySerializer(serializers.DocumentSerializer):
- class Meta:
- model = Company
- fields = '__all__'
6. ModelViewSet
- from rest_framework_mongoengine.viewsets import ModelViewSet
- class CompanyView(ModelViewSet):
- queryset = Company.objects.all()
- serializer_class = CompanySerializer
- 或
- from rest_framework_mongoengine import generics
- class CompanyView(generics.ListCreateAPIView):
- queryset = Company.objects.all()
- serializer_class = CompanySerializer
使用filter过滤
- class CompanyView(ModelViewSet):
- queryset = Company.objects.all()
- serializer_class = CompanySerializer
- my_filter_fields = ('name', 'status')
-
- def get_kwargs_for_filtering(self):
- filtering_kwargs = {}
- for field in self.my_filter_fields:
- print(field)
- print(self.request.query_params)
- field_value = self.request.query_params.get(field)
- if field_value:
- filtering_kwargs[field] = field_value
- return filtering_kwargs
-
- def get_queryset(self):
- queryset = Company.objects.all()
- filtering_kwargs = self.get_kwargs_for_filtering()
- if filtering_kwargs:
- queryset = Company.objects.filter(**filtering_kwargs)
- return queryset
7. 注册url
- from rest_framework.routers import DefaultRouter
- router = DefaultRouter()
-
- router.register(r'company', views.CompanyView, base_name='company')
-
- urlpatterns = router.urls
8. 完成,访问url
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。