2

Basically, I have a FileField and, on creation, the other fields are populated by the data extracted from this file.

Some fields of my model have a non-null contraint (a value has to be extracted from the file for those fields).

I'm using a ModelSerializer and drf fields to add allow_null to the fields (null=False in my model) as I am aware of Order of Serializer Validation in Django REST Framework.

The problem is that I want them to be readonly (I just want a form with a file input, remember ?) and according to the drf documentation : Read-only fields are included in the API output, but should not be included in the input during create or update operations.

Because of that I sometimes have to put random values in those fields just to pass the validation phase even if those fields will be populated by the correct values (extracted from the file) afterwards.

How can I ignore the non-null constraint from my model and make my fields readonly in my serializer (not changing my model) ?

Community
  • 1
  • 1
tcollart
  • 1,032
  • 2
  • 17
  • 29

2 Answers2

1

I safely removed my default validation (validators = []) as, in this particular case, I had to write the whole validation process (export all the data from my FileField to fill the others).

This enabled my serializer to do its job, without raising validation error, through the save method where I added the exported data from my file in my non null fields.

 def save(self, **kwargs):
     ...
     self.validated_data['my-non-null-field'] = value
tcollart
  • 1,032
  • 2
  • 17
  • 29
0

It's a question of design here: you are forcing the serializer to perform some of the controller's job. My recommendation would be that you will overwrite the view's create method and inside there you will build your business logic:

  • receive the file in the request; validate it's type and content
  • parse the file in a sequential (low memory footprint!) manner
  • extract your "other fields" data
  • at this stage you can call your serializer which have all his fields mapped to the model in the dB properly; delegate any validation to him, together with model creation/update;

This approach will enable you to still request only a POST from your clients while not breaking the "chain of responsibilities" and keep your serializer clean and simple.

Makes sense?

Roba
  • 646
  • 4
  • 13