Python调用父类方法时为何需传入两个参数?
Hey there! Let's figure out how to call the cleanse method from ParentSerializer in your ChildSerializer. Looking at your code, there are a couple of adjustments needed to make this work properly. Below are two practical solutions based on your use case:
方案1:让ChildSerializer继承ParentSerializer
If your ChildSerializer doesn't need to stick strictly to inheriting GenericSerializer, the simplest approach is to have it inherit from ParentSerializer directly. This lets you call the parent's cleanse method naturally via the instance itself:
from rest_framework.serializers import ModelSerializer, GenericSerializer class ParentSerializer(ModelSerializer): def cleanse(self): if hasattr(self, 'initial_data'): val1 = self.initial_data['name'] val2 = self.initial_data['age'] val3 = self.initial_data['city'] # You can modify the initial_data here if needed return self.initial_data class ChildSerializer(ParentSerializer): # Switch inheritance to ParentSerializer def is_valid(self, raise_exception=False): if hasattr(self, 'initial_data'): # Call the parent's cleanse method directly cleaned_data = self.cleanse() # Update initial_data with cleaned results if required self.initial_data = cleaned_data # Continue with the default validation logic return super().is_valid(raise_exception=raise_exception)
方案2:实例化ParentSerializer(保留GenericSerializer继承)
If ChildSerializer must inherit GenericSerializer, you can create an instance of ParentSerializer with your current data and context, then call its cleanse method:
from rest_framework.serializers import ModelSerializer, GenericSerializer class ParentSerializer(ModelSerializer): def cleanse(self): if hasattr(self, 'initial_data'): val1 = self.initial_data['name'] val2 = self.initial_data['age'] val3 = self.initial_data['city'] return self.initial_data class ChildSerializer(GenericSerializer): def is_valid(self, raise_exception=False): if hasattr(self, 'initial_data'): # Initialize ParentSerializer with current data and context parent_serializer = ParentSerializer( data=self.initial_data, context=self.context # Pass context to maintain request/other info ) # Call the cleanse method cleaned_data = parent_serializer.cleanse() # Update initial_data for subsequent validation self.initial_data = cleaned_data # Proceed with default validation return super().is_valid(raise_exception=raise_exception)
Key Notes
- The inheritance approach is better if you want to reuse all of
ParentSerializer's fields and logic inChildSerializer. - When instantiating
ParentSerializer, always pass thecontextparameter — this ensures the parent serializer has access to critical data like the request object if needed. - If your
cleansemethod modifies data, make sure to updateself.initial_dataafter calling it, so the rest of the validation process uses the cleaned values.
内容的提问来源于stack exchange,提问作者david

