在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)參數(shù)
RESTful 沒有kv, 取slug的方法為:
def retrieve(self, request, *args, **kwargs):
kwargs.get('pk')
retrieve 跨表取內(nèi)容
retrieve方法默認(rèn)會根據(jù)主鍵查找數(shù)據(jù), 多用于詳情頁, 如需使用其他字段查找, 可通過定義lookup_field來實現(xiàn), 如有更復(fù)雜的需求, 也可以重寫方法
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