1. 如何给viewset的request添加参数验证:
    首先,编写相应的serializer
class XPushSerializer(serializers.ModelSerializer):
task_id = serializers.CharField(required=False, allow_blank=True)
status = serializers.IntegerField(required=False)

class Meta:
model = models.X
fields = '__all__'
def validate(self, validated_data):
ok, msg = util.validate_required(['title', 'text', 'production_mode'], validated_data)
if not ok:
raise serializers.ValidationError(msg)

if validated_data.get('after_open') != '' and validated_data.get('after_open') not in ['go_url', 'go_app']:
msg = "'after_open'应该为'go_app' 或 'go_url',收到'%s'" % validated_data.get('after_open')
raise serializers.ValidationError(msg)
if validated_data.get('production_mode') and validated_data.get('production_mode') not in ['false', 'true']:
msg = "'production_mode'应该为'true' 或 'false',收到'%s'" % validated_data.get('production_mode')
raise serializers.ValidationError(msg)
if validated_data.get('jump_url') != '':
if not (validated_data.get('jump_url').startswith('https://') or validated_data.get('jump_url').startswith('http://')):
msg = "'jump_url'为https://或http://开头,收到" + validated_data.get('jump_url')
raise serializers.ValidationError(msg)

其次,在viewset里使用它

serializer = serializers.UmengPushSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
  1. 如何在viewset里分页
queryset = self.paginate_queryset(queryset)
return self.get_paginated_response(data)

3.如何给列表接口增加排序字段

class XViewSet(viewsets.ModelViewSet)
filter_backends = (OrderingFilter, DjangoFilterBackend)
permission_classes = (IsAuthenticated,)
ordering_fields = ('bonus_money', 'bet_money')

对X的list: ?ordering=-bonus_money表示倒序

  1. 对查询条件取或,与
# 与
queryset = X.objects.filter(name='ft',age=9)
# 或
from django.db.models import Q
queryset = X.objects.filter(Q(name='ft') | Q(age=9))
  1. 查询条件大于和小于