一步一步深入了。
相关设置技巧如下:
直接nest field显示:
class VersionPoolSerializer(serializers.ModelSerializer): site_name = serializers.ReadOnlyField(source='site_name.name') dep_version = DeployPoolSerializer(many=True, required=False, read_only=True) create_user = serializers.ReadOnlyField(source='create_user.username') class Meta: model = VersionPool fields = ('id', 'name', 'site_name', 'dep_version', 'create_user', 'add_date')
如何自定义更新有外键的记录:
class VersionPoolViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. Additionally we also provide an extra `highlight` action. """ queryset = VersionPool.objects.all() serializer_class = VersionPoolSerializer authentication_classes = (TokenAuthentication,) paginate_by = 10 def get_queryset(self): print (self.request.user, '##################') print(self.request.auth, '##################') queryset = self.queryset return queryset def create(self, request, *args, **kwargs): name = request.data['name'] site_name = request.data['site_name'] validated_data = dict() validated_data['name'] = site_name + "-" + name validated_data['site_name'] = Site.objects.get(name=site_name) validated_data['create_user'] = request.user try: VersionPool.objects.create(**validated_data) response_data = { 'name': site_name + "-" + name, 'create_user': request.user.username, 'message': 'version item save success.' } return Response(response_data, status=status.HTTP_201_CREATED) except: response_data = { 'name': site_name + "-" + name, 'create_user': request.user.username, 'message': 'version item save failed.' } return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
时间: 2024-12-04 19:56:33