Django RESTful framework 笔记

在serializer 中使用 request

重写get_queryset

router.register(r'^assistant', views.Assistant, basename='ClientUserinfo')

class Vuls(mixins.ListModelMixin,
                 GenericViewSet):
    """
    list:
        Return vuls which user managed.
    """

    serializer_class = ClientVulSerializer
    filter_backends = (filters.SearchFilter,)
    search_fields = ('vul_id', 'vul_addr',)

    def get_queryset(self):
        queryset = ScanResult.objects.using("socDB").filter(source=1)
        if not self.request.user.is_superuser:
            queryset = queryset.filter(username=self.request.user.username)
        return queryset

retrieve 取URL(GET)参数

RESTful 没有kv, 取slug的方法为:

    def retrieve(self, request, *args, **kwargs):
        kwargs.get('pk')

retrieve 跨表取内容

retrieve方法默认会根据主键查找数据, 多用于详情页, 如需使用其他字段查找, 可通过定义lookup_field来实现, 如有更复杂的需求, 也可以重写方法

class ClientInfoSerializer(serializers.ModelSerializer):

    class Meta:
        model = ClientUserinfo
        fields = '__all__'
        extra_kwargs = {'url': {'lookup_field': 'fingerprint'}}
class Assistant(ModelViewSet):

    serializer_class = ClientInfoSerializer
    lookup_field = "fingerprint"

    def get_queryset(self):
        queryset = ClientUserinfo.objects.using("socDB").filter(username=self.request.user.username).order_by(
            "-install_time")
        return queryset

    def retrieve(self, request, *args, **kwargs):
        fingerprint = self.get_object().fingerprint
        instance = ClientActiveinfo.objects.using("socDB").filter(fingerprint=fingerprint)
        serializer = ClientActiveInfoSerializer(instance, many=True)
        return Response(serializer.data)

博客文章迁移: 2019-08-01 21:31

你可能感兴趣的:(Django RESTful framework 笔记)