当前位置:   article > 正文

使用rest_framework_mongoengine生成rest API

使用rest_framework_mongoengine生成rest API

1. pip install rest_framework_mongoengine

2. 新建一个Django项目

3. 在setting.py中配置

4. 新建数据库模型

  1. import mongoengine
  2. # Create your models here.
  3. STATUS = ((0, '启用'), (1, '废弃'))
  4. class Company(mongoengine.Document):
  5. name = mongoengine.StringField(max_length=100, required=True)
  6. fullname = mongoengine.StringField(max_length=250, required=True)
  7. address = mongoengine.StringField(max_length=250)
  8. status = mongoengine.IntField(default=0, choices=STATUS, required=False)
  9. date = mongoengine.DateTimeField()
  10. meta = {'collection': 'company'}
  11. def __unicode__(self):
  12. return self.name

5. 序列化

  1. from rest_framework_mongoengine import serializers
  2. class CompanySerializer(serializers.DocumentSerializer):
  3. class Meta:
  4. model = Company
  5. fields = '__all__'

6. ModelViewSet

  1. from rest_framework_mongoengine.viewsets import ModelViewSet
  2. class CompanyView(ModelViewSet):
  3. queryset = Company.objects.all()
  4. serializer_class = CompanySerializer
  5. from rest_framework_mongoengine import generics
  6. class CompanyView(generics.ListCreateAPIView):
  7. queryset = Company.objects.all()
  8. serializer_class = CompanySerializer

使用filter过滤

  1. class CompanyView(ModelViewSet):
  2. queryset = Company.objects.all()
  3. serializer_class = CompanySerializer
  4. my_filter_fields = ('name', 'status')
  5. def get_kwargs_for_filtering(self):
  6. filtering_kwargs = {}
  7. for field in self.my_filter_fields:
  8. print(field)
  9. print(self.request.query_params)
  10. field_value = self.request.query_params.get(field)
  11. if field_value:
  12. filtering_kwargs[field] = field_value
  13. return filtering_kwargs
  14. def get_queryset(self):
  15. queryset = Company.objects.all()
  16. filtering_kwargs = self.get_kwargs_for_filtering()
  17. if filtering_kwargs:
  18. queryset = Company.objects.filter(**filtering_kwargs)
  19. return queryset

7. 注册url

  1. from rest_framework.routers import DefaultRouter
  2. router = DefaultRouter()
  3. router.register(r'company', views.CompanyView, base_name='company')
  4. urlpatterns = router.urls

8. 完成,访问url

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/437104
推荐阅读
  

闽ICP备14008679号