I have a DRF ModelSerializer, and I'm trying to override the validation, to no avail.
The reason to override the validation is that the corresponding model field is a postgresql HStoreField, so effectively a python dict. However, the incoming data is an array, and I build the corresponding dict during the create function.
Model Part:
class Report(models.Model):
report = HStoreField()
Serializer:
class ReportSerializer(serializers.ModelSerializer):
class Meta:
model = Report
fields = "__all__"
def create(self, validated_data):
codes = validated_data.pop("report")
report = {code: translate_code(code) for code in codes}
return Report(**validated_data, report=report)
def validate_report(self, value):
print("called")
return type(value) == type([]) # I know this is hacky
So the idea is to translate all of the codes to their respective translations, and save that as a key value pair. This is because I will always need the code and its translation together, and from a performance standpoint it makes more sense to do this once and save it in the db, rather than doing the translation on read.
tl;dr: Model field expects dict, data is actually list, I'm trying to override the validation of this field on the serializer to accept this.
Unfortunately, the validate_report function never seems to be called, and I'm not sure why.
EDIT
I also tried this:
class ReportSerializer(serializers.ModelSerializer):
class Meta:
model = Report
fields = "__all__"
validators = []
def create(self, validated_data):
codes = validated_data.pop("report")
report = {code: translate_code(code) for code in codes}
return Report(**validated_data, report=report)
def validate(self, data):
return isinstance(data["report"], "list")
But this validate() is not called either
EDIT: Viewset:
class ReportsViewset(viewsets.ModelViewSet):
serializer_class = ReportSerializer
viewset = Report.objects.all()